alter ignore table 添加unique key

场景:mysql

在MySQL的一张innodb引擎的表上添加一个惟一索引(uk_id),可是表中该字段有大量重复数据。sql

 

方法:数据库

 alterignore add unique index语法测试

行为相似于insert ignore,即遇到冲突的unique数据则直接抛弃而不报错。对于加惟一索引的状况来讲就是建一张空表,而后加上惟一索引,将老数据用insert ignore语法插入到新表中,遇到冲突则抛弃数据。spa

 

测试的数据库版本为5.6.22索引

mysql> select @@version;rem

+------------+
| @@version  |
+------------+
| 5.6.22-log |
+------------+

mysql> select @@old_alter_table;
+-------------------+
| @@old_alter_table |
+-------------------+
|                0 |
+-------------------+

mysql>select * from test;
+------+-------+
| id   | name  |
+------+-------+
|    1 | foo   |
|    2 | bar   |
|    3 | hello |
|    1 | world |
+------+-------+

mysql> alter table test add unique key uk_id (id);
ERROR 1062 (23000): Duplicate entry '1' for key'uk_id'

io

mysql> alter ignore table test add unique key uk_id (id);innodb

Query OK, 4 rows affected, 1 warning (0.11 sec)
Records: 4  Duplicates: 1  Warnings: 1

mysql> show warnings;
+---------+------+-----------------------------------------------------------------+
| Level   | Code | Message                                                      |
+---------+------+-----------------------------------------------------------------+
| Warning | 1681 | 'IGNORE' is deprecated andwill be removed in a future release. |
+---------+------+-----------------------------------------------------------------+table

 

查看建立惟一索引后结果,能够看到重复数据已经删除了:

mysql> select * from test;
+------+-------+
| id   | name  |
+------+-------+
|    1 | foo   |
|    2 | bar   |
|    3 | hello |
+------+-------+

 

注:此版本中,与old_alter_table的值没有关系。若是你的版本不是此版本,并且报错误(相似ERROR 1062 (23000): Duplicate entry '1' for key 'uk_id'),能够set old_alter_table = 1后再执行添加惟一键操做。