mysql alter 唯一索引_mysql对于有大量重复数据的表添加唯一索引

遇到如题的这么一个场景:需要在MySQL的一张innodb引擎的表(tableA)上添加一个唯一索引(idx_col1_u)。但是表中已经有大量重复数据,对于每个key(col1),有的重复2行,有的重复N行。

此时,做数据的手工清理,或者SQL处理无疑是非常耗时的。

1. Alter ignore table come to help

印象中MySQL有一个独有的 alter ignore add unique index的语法。

语法如下:

行为类似于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的方法还是有的,也比较直白粗暴。具体如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值