问题
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