“插入到 .. 重复密钥更新"只插入新条目而不是替换?

quot;INSERT INTO .. ON DUPLICATE KEY UPDATEquot; Only inserts new entries rather than replace?(“插入到 .. 重复密钥更新只插入新条目而不是替换?)
本文介绍了“插入到 .. 重复密钥更新"只插入新条目而不是替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,比如 table1,它有 3 列:id、number 和 name.id 是 auto_incremented.

I have a table, say table1, which has 3 columns: id, number, and name. id is auto_incremented.

我想实现一个向表中插入条目的sql语句,但是如果该行已经存在,则忽略它.

I want to achieve an sql statement which inserts entries into a table, but if the row already exists, then ignore it.

然而,

每次我跑步:

INSERT INTO table1( number, name) 
VALUES(num, name) 
ON DUPLICATE KEY 
UPDATE number = VALUES(number), 
       name = VALUES(name)

它似乎忽略了具有匹配数字和名称值的行,并且无论如何都会将条目附加到表的末尾.

It seems to ignore rows with matching number and name values and appends entries to the end of the table no matter what.

我能做些什么来防止这种情况发生吗?我觉得这与拥有 auto_incrementing 主键有关吗?谢谢

Is there anything I can do to prevent this? I have a feeling it has something to do with having the auto_incrementing primary key? thanks

推荐答案

创建一个关于数字和名称的唯一复合索引.

Create a unique composite index on number and name.

Alter table table1 Add unique index idx_unq(`number`,`name`);

然后执行 Insert Ignore INTO table1(number,name) VALUES(num, name);

这应该可以防止重复插入到表中.

That should prevent duplicate from being inserted into the table.

关于唯一索引的有用链接

这篇关于“插入到 .. 重复密钥更新"只插入新条目而不是替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)