Re: What is the postgres version of mysql's "ON DUPLICATE KEY"

From: Kevin Barnard <kevin(dot)barnard(at)gmail(dot)com>
To: Ian Linwood <pgsql-general(at)postgresql(dot)org>
Subject: Re: What is the postgres version of mysql's "ON DUPLICATE KEY"
Date: 2004-09-11 03:05:44
Message-ID: b068057c04091020052faed90f@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I may have short handed this to much. I will assume the product A has
an id of 1 and the related product B has an id of 2. You have a
default on related_counter of 1 I am assuming

INSERT INTO related_products (product_id,related_product_id)
SELECT 1, 2 WHERE NOT EXISTS (SELECT 1
FROM related_products
WHERE
product_id = 1 AND related_product_id = 2)

The insert is plain enough but instead of using values you are getting
the data from the select statement. The select statement returns 1
row of constant values just like the doing the values however no row
is returned if the where clause is not met. If no row is returned
then nothing can be inserted therefore no error is returned.

So let's look at the where clause it is a if the subselect returns any
value then exists will be true but we invert that with the NOT. The
subselect returns 1 if a row already exists with product_id and
related_product_id other wise a null row is returned.

You can think of this as a INSERT if the key doesn't already exist.
If you still need more help just let me know :-)

On Sat, 11 Sep 2004 01:17:29 +0100, Ian Linwood
<ian(at)dinwoodie(dot)freeuk(dot)com> wrote:
> Hello Kevin,
>
> Friday, September 10, 2004, 11:19:58 PM, you wrote:
>
> KB> INSERT (x,y,z) SELECT ?,?,1 WHERE NOT EXISTS (SELECT 1 FROM
> KB> related_products WHERE .....)
>
> could someone walk me through this one? I do not understand it at all.
> apologies for my cluelessness ;-)
>
> --
> Best regards,
> Ian
>
>

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2004-09-11 03:54:27 Re: SMgrRelation hashtable corrupted
Previous Message Bruce Momjian 2004-09-11 02:18:03 Re: 8.0.0beta2: gcc: unrecognized option `-pthreads'