日期:2014-05-16  浏览次数:20969 次

如何用MYSQL删除表中重复数据

?

?通常情况下,一个我们在做一个产品的时候,一开始可能由于设计考虑不周或者程序写的不够严谨,某个字段上的值产生重复了,但是又必须去掉,这个时候就稍微麻烦了一点,直接加一个?UNIQUE KEY?肯定是不行了,因为会报错。
?现在,我们来采用一种变通的办法,不过可能会丢失一些数据 :)

?在这里,我们设定一个表,其结构如下:

mysql> desc `user`;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | char(10)         | NO   |     |         |                |
| extra | char(10)         | NO   |     |         |                |
+-------+------------------+------+-----+---------+----------------+

?原来表中的数据假定有以下几条:

mysql> SELECT * FROM `user`;
+----+-------+--------+
| id | name  | extra  |
+----+-------+--------+
|  1 | user1 | user1  |
|  2 | user2 | user2  |
|  3 | user3 | user3  |
|  4 | user4 | user4  |
|  5 | user5 | user5  |
|  6 | user3 | user6  |
|  7 | user6 | user7  |
|  8 | user2 | user8  |
|  9 | USER2 | user9  |
| 10 | USER6 | user10 |
+----+-------+--------+

1、将原来的数据导出

mysql>SELECT * INTO OUTFILE '/tmp/user.txt' FROM `user`;

2、清空数据表

mysql>TRUNCATE TABLE `user`;

3、创建唯一索引,并且修改 `name` 字段的类型为?BINARY CHAR?区分大小写

mysql> ALTER TABLE `user` MODIFY `name` CHAR(10) BINARY NOT NULL DEFAULT '';

mysql> ALTER TABLE `user` ADD UNIQUE KEY ( `name` );

现在来看看新的表结构:

mysql> desc user;
+-------+------------------+------+-----+---------+----------------+
| Field | Type             | Null | Key | Default | Extra          |
+-------+------------------+------+-----+---------+----------------+
| id    | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | char(10)         | NO   | UNI |         |                |
| extra | char(10)         | NO   |     |         |                |
+-------+------------------+------+-----+---------+----------------+

4、把数据导回去,在这里,有两种选择:新的重复记录替换旧的记录,只保留最新的记录?或者是?新的记录略过,只保留最旧的记录

mysql> LOAD DATA INFILE '/tmp/user.txt' REPLACE INTO TABLE `user`;
Query OK, 10 rows affected (0.00 sec)
Records: 8  Deleted: 2  Skipped: 0  Warnings: 0

mysql> SELECT * FROM USER;
+----+-------+--------+
| id | name  | extra  |
+----+-------+--------+
|  1 | user1 | user1  |
|  8 | user2 | user8  |
|  6 | user3 | user6  |
|  4 | user4 | user4  |
|  5 | user5 | user5  |
|  7 | user6 | user7  |
|  9 | USER2 | user9  |
| 10 | USER6 | user10 |
+----+-------+--------+

?上面是采用?REPLACE?的方式,可以看到,导入过程中删掉了两条数据,结果验证确实是?新的重复记录替换旧的记录,只保留最新的记录
?现在,来看看用?IGNORE?的方式:

mysql> LOAD DATA INFILE '/tmp/user.txt' IGNORE INTO TABLE `user`;
Query OK, 6 rows affected (0.01 sec)
Records: 8  Deleted: 0  Skipped: 2  Warnings: 0

mysql> SELECT * FROM USER;
+----+-------+--------+
| id | name  | extra  |
+----+-------+--------+
|  1 | user1 | user1  |
|  2 | user2 | user2  |
|  3 | user3 | user3  |
|  4 | user4 | us