思路:有两个方法可以解决问题
方法一:
- 先通过对 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)