题解 | #删除emp_no重复的记录,只保留最小的id对应的记录。#
删除emp_no重复的记录,只保留最小的id对应的记录。
http://www.nowcoder.com/practice/3d92551a6f6d4f1ebde272d20872cf05
思路:有两个方法可以解决问题
方法一:
- 先通过对 emp_no 进行分组,找出最小的 id
select min(id) from titles_test group by emp_no
- 使用 not in 删除其他id
delete from titles_test
where id not in
(select * from (select min(id) from titles_test group by emp_no) as tmp);
方法二:
- 我们首先找出所有出现频次 > 1 的 emp_no 及 id
select min(id) as id, emp_no
from titles_test
group by emp_no
having count(emp_no) > 1
- 然后我们连接 titles_test 表,找出所有需要删除的 id
select a.id
from titles_test as a, (select min(id) as id, emp_no
from titles_test
group by emp_no
having count(emp_no) > 1) as b
where a.emp_no = b.emp_no and a.id > b.id
- 最后根据 id 删除数据
delete from titles_test
where id in (select * from (select a.id
from titles_test as a, (select min(id) as id, emp_no
from titles_test
group by emp_no
having count(emp_no) > 1) as b
where a.emp_no = b.emp_no and a.id > b.id
) as tmp)
SQL练习 文章被收录于专栏
已完成牛客的SQL练习。接下来是算法的练习