如果不存在则插入 [英] INSERT if not Exist Mysql
问题描述
我有这张桌子
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屋!