简体   繁体   中英

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

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.

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();

There are 4 methods listed in the below link, please have a look and use whichever suits you.

Method 1: SELECT, then INSERT Method 2: try { INSERT } catch { SELECT } Method 3: INSERT IGNORE then SELECT Method 4: INSERT INTO… ON DUPLICATE KEY UPDATE

http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/

Here is the mysql state to insert if not exists and return the id either it new insertion or old

    INSERT INTO `tags` (`tag`) 
SELECT 'myvalue1' 
FROM tags
WHERE NOT EXISTS (SELECT id FROM `tags` WHERE `tag`='myvalue1') 
LIMIT 1;
select * from brand where `tag`='myvalue1'

Insert into a MySQL table or update if exists

this would resolve your issue? I think that would resolve most of your issues if you translate his answer into a format which works for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM