Getting last insert id for mysql after Insert

2019-07-18 03:26发布

问题:

I have a query like so:

INSERT INTO table1 (field1,field2) VALUES ('$value1','$value2') ON DUPLICATE KEY UPDATE field1 = '$value1'

I then want to get the last insert id if it does the insert, how can I do this? If the query ends up doing an update I dont want the last insert id. Is there a way to determine if it did an update or a insert?

回答1:

I guess I should of searched the site before posting. Basically adding this worked:

id=LAST_INSERT_ID(id)

On the on duplicate update. I found that answer here:

Duplicate Key Last Insert ID



回答2:

According to this MySQL Manual Page:

If a table contains an AUTO_INCREMENT column and INSERT ... ON DUPLICATE KEY UPDATE inserts or updates a row, the LAST_INSERT_ID() function returns the AUTO_INCREMENT value.



标签: mysql insert