Getting last insert id for mysql after Insert

2019-07-18 03:10发布

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?

标签: mysql insert
2条回答
【Aperson】
2楼-- · 2019-07-18 04:03

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

查看更多
祖国的老花朵
3楼-- · 2019-07-18 04:05

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.

查看更多
登录 后发表回答