简体   繁体   English

插入前检查SQL表中是否存在具有相同唯一ID的记录

[英]Check if a record with the same unique ID exists in SQL table before insert

How can I check if there's another record in the table with the same unique ID (the column name is ID ), then and if one exists not do anything, otherwise insert the record? 我如何检查表中是否还有另一条记录具有相同的唯一ID(列名是ID ),然后如果存在则不执行任何操作,否则插入记录?

Do I need to index the ID column and set it as unique/primary key? 我是否需要索引ID列并将其设置为唯一/主键?

One option is to use INSERT IGNORE . 一种选择是使用INSERT IGNORE As the name implies it will INSERT rows that do not exist, and it will do nothing with duplicate rows. 顾名思义,它将插入不存在的行,并且对重复的行将不执行任何操作。

CREATE TABLE Table1 (
`id` int NOT NULL PRIMARY KEY, 
`foo` varchar(20) 
);

INSERT IGNORE INTO Table1
    (`id`, `foo`)
VALUES
    (1, 'a'),
    (2, 'a'),
    (3, 'a'),
    (4, 'a'),
    (1, 'a'),
    (2, 'a'),
    (1, 'a');

The above will only insert the first 4 rows. 上面只会插入前4行。 The final 3 rows are not inserted because they have duplicate keys. 最后三行没有插入,因为它们具有重复的键。

SQL Fiddle Demo SQL小提琴演示

INSERT IGNORE requires that you have either a primary key or unique index. INSERT IGNORE要求您具有主键或唯一索引。

More info on INSERT IGNORE (as well as other ways to handle duplicates) here: MySQL Handling Duplicates 有关INSERT IGNORE (以及其他处理重复项的方法)的更多信息,请INSERT IGNOREMySQL处理重复项

您可以使用REPLACE作为INSERT OR UPDATE

In case you want to change it to also do something when the id alreadt exists, here's a snippet: 如果您想将其更改为在id已经存在时也做一些事情,请参考以下代码段:

INSERT INTO table (key1, ...) VALUES (value1, ...) ON DUPLICATE KEY UPDATE dosomethingelse

So if the key already exists it will update whatever is after on duplicate key , else it will insert whatever is before that. 因此,如果密钥已经存在,它将更新on duplicate key之后的on duplicate key ,否则它将插入之前的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM