对于有大量重复数据的表添加唯一索引
遇到如题的这么一个场景:需要在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] TABLEtbl_name
行为类似于insert ignore,即遇到冲突的unique数据则直接抛弃而不报错。对于加唯一索引的情况来说就是建一张空表,然后加上唯一索引,将老数据用insert ignore语法插入到新表中,遇到冲突则抛弃数据。
文档中对于alter ignore的注释:详见:http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
IGNORE
is a MySQL extension to standard SQL. It controls howALTER TABLE
works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. IfIGNORE
is not specified, the copy is aborted and rolled back if duplicate-key errors occur. IfIGNORE
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
详见:http://bugs.mysql.com/bug.php?id=40344
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)
具体原理:http://dev.mysql.com/doc/refman/5.1/en/server-system-variables.html#sysvar_old_alter_table
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?