准备
数据表:
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)最大的一条。
方法一
- 查询出重复的组中每组最大的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)
- 查询出需要删除的记录的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)
- 删除记录
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
方法二
- 查询每组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)
- 删除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)