Mysql删除某字段中有重复数据的行

有一次业务需求变更,需要将web_user_mobile_time_limit中的mobile字段值设置为唯一。
原有表结构如下:
mysql> desc web_user_mobile_time_limit;
+----------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| mobile | varchar(20) | YES | | NULL | |
| dateTime | timestamp | YES | | CURRENT_TIMESTAMP | |
+----------+-------------+------+-----+-------------------+----------------+

如果mobile字段没有重复数据,可以执行下一行语句修改表结构:
Alter table web_user_mobile_time_limit add unique(mobile);

由于现有表的mobile字段的数据已经有一些是重复的。
mysql> select * from web_user_mobile_time_limit;
+----+-------------+---------------------+
| id | mobile | dateTime |
+----+-------------+---------------------+
| 1 | 13800138000 | 2014-09-23 20:18:17 |
| 2 | 13800138000 | 2014-09-23 20:18:57 |
| 3 | 13800138001 | 2014-09-23 20:19:04 |
| 4 | 13800138000 | 2014-09-23 20:19:18 |
| 5 | 13800138001 | 2014-09-23 20:19:22 |
| 6 | 13800138002 | 2014-09-23 20:19:25 |
| 7 | 13800138001 | 2014-09-23 20:19:29 |
| 8 | 13800138002 | 2014-09-23 20:19:34 |
| 9 | 13800138003 | 2014-09-23 20:19:39 |
| 10 | 13800138004 | 2014-09-23 20:19:43 |
| 11 | 13800138004 | 2014-09-23 20:19:46 |
+----+-------------+---------------------+
11 rows in set

在修改表结构的过会提示如下错误:
mysql> Alter table web_user_mobile_time_limit add unique(mobile);
ERROR 1062 : Duplicate entry '13800138000' for key 'mobile'

业务部门的需求是直接删除掉重复数据中更新时间较晚的数据,执行方法是这样:
delete from a using web_user_mobile_time_limit as a,web_user_mobile_time_limit as b where a.id>b.id and a.mobile = b.mobile;
如果想保留较旧的数据则执行:
delete from a using web_user_mobile_time_limit as a,web_user_mobile_time_limit as b where a.id<b.id and a.mobile = b.mobile;

再次查看结果如下:
mysql> select * from web_user_mobile_time_limit;
+----+-------------+---------------------+
| id | mobile | dateTime |
+----+-------------+---------------------+
| 1 | 13800138000 | 2014-09-23 20:18:17 |
| 3 | 13800138001 | 2014-09-23 20:19:04 |
| 6 | 13800138002 | 2014-09-23 20:19:25 |
| 9 | 13800138003 | 2014-09-23 20:19:39 |
| 10 | 13800138004 | 2014-09-23 20:19:43 |
+----+-------------+---------------------+
5 rows in set
至此,重复数据已经删除,现在修改表结构就不会报错了;

mysql> Alter table web_user_mobile_time_limit add unique(mobile);
mysql> desc web_user_mobile_time_limit;
+----------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| mobile | varchar(20) | YES | UNI | NULL | |
| dateTime | timestamp | YES | | CURRENT_TIMESTAMP | |
+----------+-------------+------+-----+-------------------+----------------+
3 rows in set

发表回复

您的电子邮箱地址不会被公开。