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

From: Kevin Barnard <kevin(dot)barnard(at)gmail(dot)com>
To: Gaetano Mendola <mendola(at)bigfoot(dot)com>
Cc: Nick <nboutelier(at)hotmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: What is the postgres version of mysql's "ON DUPLICATE KEY"
Date: 2004-09-10 22:19:58
Message-ID: b068057c04091015195db1e2fc@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

UPDATE related_products SET related_counter = related_counter
WHERE .....

only updates if the record exists

INSERT (x,y,z) SELECT ?,?,1 WHERE NOT EXISTS (SELECT 1 FROM
related_products WHERE .....)

Inserts if the key does not exist.

On Sat, 11 Sep 2004 00:02:26 +0200, Gaetano Mendola <mendola(at)bigfoot(dot)com> wrote:
> Nick wrote:
>
> > I have a table with columns
> > (product_id,related_product_id,related_counter)
> >
> > If product A is related to product B then a record should be created,
> > if the record already exists then the related_counter should be
> > incremented.
> >
> > This is very easy to do with MySQL using INSERT... ON DUPLICATE KEY.
> > Standard or not, it is very usefull.
> >
> > Is there a way to catch the insert error. For example...
> >
> > INSERT INTO related_products (product_id,related_product_id) VALUES
> > (?,?);
> > IF (???error: duplicate key???) THEN
> > UPDATE related_products SET related_counter = related_counter + 1;
> > END IF;
> >
> > -Nick
>
> With a rule you can do it easily ( never tried ).
>
> Regards
> Gaetano Mendola
>
> ---------------------------(end of broadcast)---------------------------
> TIP 4: Don't 'kill -9' the postmaster
>

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2004-09-10 22:33:21 Re: Speeding up LIKE with placeholders?
Previous Message Dan Sugalski 2004-09-10 22:17:27 Re: Speeding up LIKE with placeholders?