MySQL on duplicate key… get existing ID?

筅森魡賤 提交于 2021-02-17 05:44:07

问题


I'm using ON DUPLICATE KEY UPDATE to handle duplicate inserts on a table, in order that they are discarded.

In my case it's a simple table storing tags:

  • id (int, PK, AI, unsigned, not null)
  • tag (varchar 25, not null, unique)

This is working fine, but I need to retrieve the ID - either the insert ID, on successful insert, or the existing ID, if it's a duplicate.

I'm getting insert ID = 0 where ON DUPLICATE KEY UPDATE fires, which I guess is expected behaviour since no insert took place.

Is there anyway I can get the existing ID, or am I headed to a separate read query?


回答1:


You could add a third column ModifiedDate and use that:

insert into t(id, tag)
    select id, tag
    on duplicate key update ModifiedDate = now();

This will ensure that an update really occurs, and in turn, that LAST_INSERT_ID() returns a value.



来源:https://stackoverflow.com/questions/24455666/mysql-on-duplicate-key-get-existing-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!