views:

2851

answers:

5

I have the following query:

INSERT INTO table (a) VALUES (0) ON DUPLICATE KEY UPDATE a=1

I want the ID of either the insert or the update. Usually I run a second query in order to get this as I believe insert_id() only returns the 'inserted' ID and not the updated ID.

Is there a way to INSERT/UPDATE and retrieve the ID of the row without running two queries?

Thanks, Kevin

Update: So the answer looks like this:

INSERT INTO table (a) VALUES (0) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)

Thanks all!

A: 

You might look at REPLACE, which is essentially a delete/insert if the record exists. But this would change the auto increment field if present, which could break relationships with other data.

Brent Baisley
Ah yeah - I'm looking for something that won't get rid of previous ID's
thekevinscott
+1  A: 

Dumb question: If you're using an auto-incremented index, why would it already exist?

jedihawk
the a columns is not autoincrement but a unique key for example
solomongaby
A: 

I don't know what is your version of MySQL but with InnoDB, there was bug with autoinc

bug in 5.1.20 and corrected in 5.1.23 http://bugs.mysql.com/bug.php?id=27405

bug in 5.1.31 and corrected in 5.1.33 http://bugs.mysql.com/bug.php?id=42714

Hugues Van Landeghem
+7  A: 

Check this page out: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
At the bottom of the page they explain how you can make LAST_INSERT_ID meaningful for updates by passing an expression to that MySQL function.

fredrik
Somehow I missed that when looking at that page.So the update portion appears as :UPDATE id=LAST_INSERT_ID(id)And that works great. Thanks!
thekevinscott
Glad I could help!
fredrik
It is said that php function mysql_insert_id() returns correct value in both cases: http://www.php.net/manual/en/function.mysql-insert-id.php#59718.
jayarjo
A: 

It's worth noting, and this might be obvious (but I'll say it anyway for clarity here), that REPLACE will blow away the existing matching row before inserting your new data. ON DUPLICATE KEY UPDATE will only update the columns you specify and preserves the row.

From the manual:

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

Greg K