Mysql删除重复数据

准备

数据表:

mysql> select * from students;
+---------+-----+--------+
| name    | age | stu_id |
+---------+-----+--------+
| lisi    |  19 |      1 |
| aaa     |  10 |      2 |
| bbb     |  10 |      3 |
| ccc     |  19 |      4 |
| ddd     |  19 |      5 |
| eee     |  20 |      6 |
| fff     |  20 |      7 |
| zhansan |  11 |     11 |
| laowang |  10 |     12 |
| wangwu  |  20 |     13 |
+---------+-----+--------+
10 rows in set (0.00 sec)

需求:

删除年龄重复的数据,并保留学号(stu_id)最大的一条。

方法一

  1. 查询出重复的组中每组最大的ID
mysql> SELECT age, MAX(stu_id) as max_id from students GROUP BY age HAVING count(*) > 1;
+-----+--------+
| age | max_id |
+-----+--------+
|  10 |     12 |
|  19 |      5 |
|  20 |     13 |
+-----+--------+
3 rows in set (0.00 sec)

  1. 查询出需要删除的记录的ID
mysql> select t1.* from students t1, (SELECT age, MAX(stu_id) as max_id from students GROUP BY age HAVING count(*) > 1) as t2 WHERE t1.age=t2.age and t1.stu_id<t2.max_id;
+------+-----+--------+
| name | age | stu_id |
+------+-----+--------+
| lisi |  19 |      1 |
| aaa  |  10 |      2 |
| bbb  |  10 |      3 |
| ccc  |  19 |      4 |
| eee  |  20 |      6 |
| fff  |  20 |      7 |
+------+-----+--------+
6 rows in set (0.00 sec)
  1. 删除记录
DELETE t1 from students as t1, (SELECT age, MAX(stu_id) as max_id from students GROUP BY age HAVING count(*) > 1) as t2 WHERE t1.age=t2.age and t1.stu_id < t2.max_id

方法二

  1. 查询每组ID最大的记录
mysql> select max(stu_id) as max_id from students GROUP BY age;
+--------+
| max_id |
+--------+
|     12 |
|     11 |
|      5 |
|     13 |
+--------+
4 rows in set (0.00 sec)
  1. 删除ID不是max_id的记录
DELETE from students WHERE stu_id not in (SELECT f.max_id from (select max(stu_id) as max_id from students GROUP BY age) f)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值