Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the primary key after a DUPLICATE KEY error?

Tags:

sql

php

mysql

If I run an insert query but it fails because of duplicated key error is there any way to get its primary key without doing another select?

Basically:

INSERT INTO tbl (field) VALUES ('myvalue')

This fails because there is already a record with ID:1 and field:myvalue.

Now I Want to know that ID:1 without doing another query:

SELECT id FROM tbl WHERE field = 'myvalue'

is it possibile?

like image 659
dynamic Avatar asked Nov 22 '25 14:11

dynamic


1 Answers

Here is a link that provides four different ways to deal with this: http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/

like image 59
Christopher Masser Avatar answered Nov 25 '25 03:11

Christopher Masser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!