如果不存在则插入 [英] INSERT if not Exist Mysql

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

问题描述

我有这张桌子

id     follow_id    follower_id
 1  |       2     |      3
 2  |       2     |      4
 3  |       2     |      5
 4  |       2     |      6
 5  |       3     |      7
 6  |       3     |      8

我想跳过如果我尝试插入"couple" follow_id 2,follower_id 3,而无需对性能进行子查询

I'd like to skip If i try to insert the "couple" follow_id 2, follower_id 3 without do subquery for the performance

我可以在重复键更新中执行INSERT ...操作吗?

can I do INSERT... ON DUPLICATE KEY UPDATE or something of this?

更新,适用于symfony用户

回答后.我使用Symfony,并且这样做

after answers. i Use Symfony, and for do

UNIQUE INDEX followee_and_follower (follow_id,follower);

http://docs.doctrine- project.org/en/2.0.x/reference/annotations-reference.html#uniqueconstraint

推荐答案

其官方语法是

INSERT IGNORE ...

但是,在您的情况下,这样做实际上更可取

However, in your case it may actually be preferable to do

INSERT ... ON DUPLICATE KEY UPDATE id=id

请参见

See benchmarks. In my experience, this hack only improves performance if you've got a primary key--the optimizer won't recognize the no-op if you do follower_id = follower_id.

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

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