简体   繁体   中英

MySQL ignoring duplicates on non-primary key

I have a table created by this SQL statement:

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. 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. I'm not sure why you don't want to make it a unique index.

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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