Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql: insert record if not exists else return the id of record

Tags:

i need to insert unique values in a table, and need the ids of records, need to insert those id's in relationship table, need the query to insert the record if not exists return the inset id, if exists return the record primary key(id).

and i want to do this for multiple values, like orange, mango, banana, like batch insert.

schema:

------------ id | tag   | ------------ 1  | orange| ------------ 

i have trid this for a single record

INSERT INTO `tags` (`tag`)  SELECT 'myvalue1'  FROM tags WHERE NOT EXISTS (SELECT 1 FROM `tags` WHERE `tag`='myvalue1')  LIMIT 1 

posted the question to figure out some optimized solution, i don't want to use extra loops in the code to match the values from db.

like image 372
Abuzer Firdousi Avatar asked Dec 09 '13 20:12

Abuzer Firdousi


1 Answers

There is an example on the documentation page for INSERT ... ON DUPLICATE KEY UPDATE:

Your query would look like this:

INSERT INTO `tags` (`tag`) VALUES ('myvalue1')   ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), `tag`='myvalue1'; SELECT LAST_INSERT_ID(); 
like image 66
Marcus Adams Avatar answered Oct 11 '22 22:10

Marcus Adams