且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL-忽略插入错误:重复输入

更新时间:2023-01-22 16:40:44

您可以使用

You can use INSERT... IGNORE syntax if you want to take no action when there's a duplicate record.

如果您愿意,可以使用替换成语法用相同的密钥用新记录覆盖旧记录.

You can use REPLACE INTO syntax if you want to overwrite an old record with a new one with the same key.

或者,您可以使用 INSERT ... ON如果您想对记录执行更新,而在遇到重复项时则使用DUPLICATE KEY UPDATE 语法.

Or, you can use INSERT... ON DUPLICATE KEY UPDATE syntax if you want to perform an update to the record instead when you encounter a duplicate.

以为我会添加一些示例.

Thought I'd add some examples.

假设您有一个名为tbl的表,该表有两列idvalue.只有一个条目,id = 1,value = 1.如果运行以下语句:

Say you have a table named tbl with two columns, id and value. There is one entry, id=1 and value=1. If you run the following statements:

REPLACE INTO tbl VALUES(1,50);

您仍然有一条记录,id = 1值= 50.请注意,整个记录首先被删除,然后重新插入.然后:

You still have one record, with id=1 value=50. Note that the whole record was DELETED first however, and then re-inserted. Then:

INSERT IGNORE INTO tbl VALUES (1,10);

该操作成功执行,但未插入任何内容.您仍然具有id = 1和value = 50.最后:

The operation executes successfully, but nothing is inserted. You still have id=1 and value=50. Finally:

INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;

您现在有一条ID为1且值为200的记录.

You now have a single record with id=1 and value=200.