1. 程式人生 > >對於有大量重複資料的表新增唯一索引

對於有大量重複資料的表新增唯一索引

遇到如題的這麼一個場景:需要在MySQL的一張innodb引擎的表(tableA)上新增一個唯一索引(idx_col1_u)。但是表中已經有大量重複資料,對於每個key(col1),有的重複2行,有的重複N行。

此時,做資料的手工清理,或者SQL處理無疑是非常耗時的。

1. Alter ignore table come to help

印象中MySQL有一個獨有的 alter ignore add unique index的語法。

語法如下:

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name

行為類似於insert ignore,即遇到衝突的unique資料則直接拋棄而不報錯。對於加唯一索引的情況來說就是建一張空表,然後加上唯一索引,將老資料用insert ignore語法插入到新表中,遇到衝突則拋棄資料。

IGNORE is a MySQL extension to standard SQL. It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only the first row is used of rows with duplicates on a unique key. The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.

2.   #1062 - Duplicate entry

 然而在執行了 alter ignore table tableA add unique index idx_col1_u (col1) 後,還是報了以下錯誤:

 #1062 - Duplicate entry '111' for key 'col1'.

不是會自動丟棄重複資料麼?世界觀被顛覆了。查了下資料原來是alter ignore的語法不支援innodb。

得知alter ignore的實現完全取決於儲存引擎的內部實現,而不是server端強制的,具體描述如下:

For ALTER TABLE with the IGNORE keyword, IGNORE is now part of the information provided to the storage engine. It is up to the storage engine whether to use this when choosing between the in-place or copy algorithm for altering the table. For InnoDB index operations, IGNORE is not used if the index is unique, so the copy algorithm is used
3. 解決方案

當然解決這個問題的tricky的方法還是有的,也比較直白粗暴。具體如下:

ALTER TABLE tableA ENGINE MyISAM;
ALTER IGNORE TABLE tableA ADD UNIQUE INDEX idx_col1_u (col1)
ALTER TABLE table ENGINE InnoDB;

updated in 2013-09-26:

@jyzhou 分享提到,可以不用改成MyISAM,而直接使用set old_alter_table = 1; 的方法。具體做法如下:

set old_alter_table = 1;

ALTER IGNORE TABLE tableA ADD UNIQUE INDEX idx_col1_u (col1)