mysql對於有大量重複數據的表添加唯一索引

例如,user表中有user_id,user_name兩個字段,如果不希望有兩條一摸一樣的的user_id和user_name,我們可以給user表添加兩個字段的聯合唯一索引:
alter table user add unique index(user_id,user_name);


這樣當向表中添加相同記錄的時候,會返回1062的添加失敗信息。
但是有一種情況是表中已經有n個重複的記錄,這時候我們纔想起來要添加唯一索引,再執行上面的操作時,數據庫會告訴你已經有重複的記錄了,建立索引失敗,這時候,我們可以用下面的操作:

alter ignore table user add unique index(user_id,user_name);


它會刪除重複的記錄(別怕,會保留一條),然後建立唯一索引,高效而且人性化。

然而在執行了 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

 詳見:http://bugs.mysql.com/bug.php?id=40344

當然解決這個問題的tricky的方法還是有的。具體如下:

1、

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

2、

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

set old_alter_table = 1;

ALTER IGNORE TABLE tableA ADD UNIQUE INDEX idx_col1_u (col1) 


發佈了91 篇原創文章 · 獲贊 49 · 訪問量 36萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章