MySQL inserts data insert ignore, duplicate data is automatically ignored

When inserting data in MySQL, if the inserted data already exists in the table (primary key or unique key already exists), use the insert ignore syntax to ignore inserting duplicate data.

1. insert ignore syntax

insert ignore into table_name values…

When using the insert ignore syntax to insert data, if a primary key or unique key conflict occurs, the inserted data will be ignored.

One of the following conditions is met:

  • duplicate primary key
  • Duplicate unique key

2. Insert ignore case

First look at a table, table name table_name, primary key id, unique key name, the specific table structure and data in the table are as follows:

 CREATE TABLE table_name(
  id int(11) NOT NULL,
  name varchar(50) DEFAULT NULL,
  age int(11) DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uk_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
mysql> select * from table_name;
+----+------+------+
| id | name | age  |
+----+------+------+
|  1 | Tom  |   20 |
+----+------+------+

2.1 Primary key conflict

Insert a record with an id of 1. If ignore is not added, a primary key conflict error will be reported, as follows:

mysql> insert into table_name values(1,’Bill’, 21);
ERROR 1062 (23000): Duplicate entry ‘1for keyPRIMARY

After adding ignore, no error will be reported, but there is a warning warning, as follows:

mysql> insert ignore into table_name values(1,’Bill’, 21);
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show warnings;
+———+——+—————————————+
| Level   | Code | Message                               |
+———+——+—————————————+
| Warning | 1062 | Duplicate entry ‘1for keyPRIMARY|
+———+——+—————————————+

Query the table and find that the inserted data is ignored.

mysql> select * from table_name;
+-+——+——+
| id | name | age  |
+-+——+——+
|  1 | Tom  |   20 |
+-+——+——+

2.2 Unique key conflicts

Likewise, inserting data with unique key violations is ignored, as follows:

mysql> insert into table_name values(2,’Tom’,21);
ERROR 1062 (23000): Duplicate entry ‘Tom’ for key ‘uk_name’

mysql> insert ignore into table_name values(2,’Tom’,21);
Query OK, 0 rows affected, 1 warning (0.00 sec)

If the business logic needs to automatically ignore when inserting duplicate data, try MySQL's insert ignore function.

Guess you like

Origin blog.csdn.net/doublepg13/article/details/128237992