在INSERT语句中,使用IGNORE关键字时,在INSERT语句执行过程中发生的错误将会被忽略。例如,当向建有UNIQUE索引或主键的字段插入重复字段时,会导致duplicate-key错误,执行的语句会失败。当带有IGNORE关键字时,这个错误会被忽略,只会产生警告。
当向分区表插入数据时,IGNORE关键字具有类似的效果。当没有要插入的分区时,MySQL会忽略错误。
当数据转换引发报错时,可以通过IGNORE关键字来忽略错误,这时MySQL会产生警告而不退出语句的执行,无效的数值会被调整成接近的数值并被插入。
mysql> desc t10;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | 0 | |
| name | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> select * from t10;
+----+--------+
| id | name |
+----+--------+
| 10 | Neo |
| 20 | Lucy |
| 30 | Lily |
| 50 | Dingyi |
| 60 | Jones |
+----+--------+
5 rows in set (0.00 sec)
mysql> desc t7;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int(10) | NO | PRI | 0 | |
| name | varchar(15) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> select * from t7;
+----+--------+
| id | name |
+----+--------+
| 50 | Dingyi |
| 60 | Jones |
+----+--------+
2 rows in set (0.00 sec)
mysql> insert into t7 select * from t10;
ERROR 1062 (23000): Duplicate entry '50' for key 'PRIMARY'
mysql> select * from t7;
+----+--------+
| id | name |
+----+--------+
| 50 | Dingyi |
| 60 | Jones |
+----+--------+
2 rows in set (0.00 sec)
mysql> select * from t10;
+----+--------+
| id | name |
+----+--------+
| 10 | Neo |
| 20 | Lucy |
| 30 | Lily |
| 50 | Dingyi |
| 60 | Jones |
+----+--------+
5 rows in set (0.00 sec)
mysql> insert ignore into t7 select * from t10;
Query OK, 3 rows affected, 1 warning (0.00 sec)
Records: 5 Duplicates: 2 Warnings: 1