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)
参与评论 您还未登录,请先 登录 后发表或查看评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

Shaun-Y

生活太南,全靠赏饭

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值