开发者

Can I get the IDs of all updated rows?

Suppose I do an INSERT / ON DUPLICATE KEY UPDATE in MySQL, and it updates a bunch of rows. And the开发者_如何学C table has an autoincrement primary key.

Is there any easy way to get MySQL to tell me the IDs of the rows it just updated?

I know I can do another SELECT query that looks for the same constraints that the INSERT statement used, and that's not hard to write, but it seems like it could be much more efficient if MySQL could just keep track of the IDs for me.

I saw the trick in the manual about LAST_INSERT_ID for the case where there's a single inserted/updated row, but I'm wondering about the case where you're updating many rows.


Check this link once

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

It says

If a table contains an AUTO_INCREMENT column and INSERT ... UPDATE inserts a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value. If the statement updates a row instead, LAST_INSERT_ID() is not meaningful. However, you can work around this by using LAST_INSERT_ID(expr). Suppose that id is the AUTO_INCREMENT column.

To make LAST_INSERT_ID() meaningful for updates, insert rows as follows:

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3;


Efficiency aside, unless you use "Select for Update" (keep rows locked), you can't even be guaranteed that your subsequent Select will pick up the SAME rows you just updated so even a second read is not foolproof.
Triggers are fairly inefficient in MYSQL, but if you really need to do this, create trigger(s) [for update, insert] on the table in question, and have it insert the ID's of modified rows into another table. You need to store connection_id() (of your current session) so you can separate rows inserted by statements on another session.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜