开发者

How to get ID row of updated row?

This is my query:

INSERT INTO table (value) VALUES (value) ON DUPLICATE KEY UPDATE value=value

With mysql_insert_id() I get the new inserted ID, but how to get the ID of row updated?

I tri开发者_Go百科ed mysql_insert_id() but, for updated row, I get 0.


MySQL ON DUPLICATE KEY - last insert id?

"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."


There's no way to do that. You could do SELECT id FROM table WHERE value = value;


Well since you already have a WHERE statement you can select it with a different query. mysql_insert_id() does exactly what it says. Get an ID from an INSERT.


Starting with MySQL 5.1.12, it's possible. MySQL's last_insert_id function will return the value of the autoincrement field for both insert and update operations.


You'll get the insert id with the mysql_insert_id() php function.

However when combined with ON DUPLICATE KEY UPDATE, you'll have to do a bit more if you want mysql_insert_id() to give you the key that was updated, instead of the new key generated that was inserted.

Change your SQL to

INSERT INTO table (value) VALUES (value) 
       ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id),value=value;

See more info here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜