mysql 记录不存在返回,mysql:如果不存在则插入记录,否则返回记录的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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值