mysql:如果不存在,则插入记录,否则返回记录的id [英] mysql: insert record if not exists else return the id of record

查看:741
本文介绍了mysql:如果不存在,则插入记录,否则返回记录的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在表中插入唯一值,并且需要记录的ID,需要在关系表中插入这些ID, 需要查询以插入记录(如果不存在)返回插入ID,如果存在则返回记录主键(ID).

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.

模式:

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

发布了问题以找出一些优化的解决方案,我不想在代码中使用额外的循环来匹配db中的值.

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:

您的查询将如下所示:

INSERT INTO `tags` (`tag`) VALUES ('myvalue1')
  ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), `tag`='myvalue1';
SELECT LAST_INSERT_ID();

这篇关于mysql:如果不存在,则插入记录,否则返回记录的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆