MySQL 在重复键忽略?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2366813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:25:59  来源:igfitidea点击:

On duplicate key ignore?

mysql

提问by Good-bye

I'm trying to finish this query; my tag field is set to UNIQUE and I simply want the database to ignore any duplicate tag.

我正在尝试完成此查询;我的标签字段设置为 UNIQUE,我只是希望数据库忽略任何重复的标签。

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY IGNORE '*the offending tag and carry on*'

or even this would be acceptable

甚至这是可以接受的

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c')
ON DUPLICATE KEY UPDATE '*the offending tag and carry on*'

回答by thummper

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tagis the unique key, use:

建议不要使用 INSERT IGNORE,因为它会忽略所有错误(即它是一个草率的全局忽略)。相反,由于在您的示例中tag是唯一键,请使用:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

在重复键上产生:

Query OK, 0 rows affected (0.07 sec)

查询正常,0 行受影响(0.07 秒)

回答by Byron Whitlock

Mysql has this handy UPDATE INTOcommand ;)

Mysql 有这个方便的UPDATE INTO命令;)

editLooks like they renamed it to REPLACE

编辑看起来他们将其重命名为 REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

REPLACE 的工作方式与 INSERT 完全相同,不同之处在于如果表中的旧行与 PRIMARY KEY 或 UNIQUE 索引的新行具有相同的值,则在插入新行之前删除旧行