简体   繁体   English

MySQL忽略非主键上的重复项

[英]MySQL ignoring duplicates on non-primary key

I have a table created by this SQL statement: 我有一个通过此SQL语句创建的表:

CREATE TABLE employees (
    id  INTEGER  NOT NULL AUTO_INCREMENT,
    name   VARCHAR(20),
    PRIMARY KEY (id)
);

I would like to insert into the table using something like 我想使用类似的东西插入表格

INSERT IGNORE INTO employees (name) values ('foo');

but for that statement to do nothing if there is already a person with a name 'foo' in the table. 但对于该语句,如果表中已经存在一个名为“ foo”的人,则不执行任何操作。 Is there a statement out there that ignores duplicates on a field other than a primary key or a field that is defined as unique? 是否有一条语句可以忽略除主键或定义为唯一的字段以外的其他字段上的重复项?

INSERT INTO employees (name)
SELECT "foo" name FROM (select count(*) c
                        from employees
                        where name = "foo"
                        having c = 0) x;

You should have an index on name for efficiency. 您应该在name上建立索引以提高效率。 I'm not sure why you don't want to make it a unique index. 我不确定为什么您不想使其成为唯一索引。

FIDDLE 小提琴

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

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