> 데이터 베이스 > MySQL 튜토리얼 > 对于有大量重复数据的表添加唯一索引_MySQL

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-01 13:29:57
원래의
1604명이 탐색했습니다.

bitsCN.com

遇到如题的这么一个场景:需要在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 <em class="replaceable"><code>tbl_name</code></em>
로그인 후 복사

行为类似于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 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 theinformation provided to the storage engine. It is up to the storageengine whether to use this when choosing between the in-place or copyalgorithm 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;

 

 

 

 

 

 

bitsCN.com
관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
HTML 요약
에서 1970-01-01 08:00:00
0
0
0
HTML 요약
에서 1970-01-01 08:00:00
0
0
0
node.js - gulp.task 비동기 문제
에서 1970-01-01 08:00:00
0
0
0
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿