S
S
sim2q2020-05-27 12:57:22
MySQL
sim2q, 2020-05-27 12:57:22

How to immediately get the AUTO_INCREMENT id of a duplicate record on INSERT?

A frequent case when you need to insert a record, and if there is already a record with such a UNIQ key, then return the AUTO_INCREMENT ID field for this record.
Now I'm doing it in the forehead:

if(mysql_query("INSERT INTO tab (hash) VALUE ('hash')"))
  {
  if(mysql_errno()== ER_DUP_KEY)
    {
    mysql_query("SELECT id FROM tab WHERE hash = 'hash'");
    }
  }

But in theory, the server inside has already felt this entry and knows where it is :)
ps INSERT ... ON DUPLICATE KEY UPDATE unfortunately will not return an AUTO_INCREMENT column for the case with UPDATE

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Gordinskiy, 2020-05-27
@sim2q

Let's say this:

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

S
sim2q, 2020-05-27
@sim2q

Holmes, but how? :)
It works, but I don't understand.
The only drawback is that each hit in a duplicate generates INCREMENT, I'll try to test which is cheaper

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question