mysql删除重复元素并保留最小的标号

delete from person where Id not in(select min(id)from (select *from person)c group by c.email) and
id in(select id from(select *from person)g where id in (select h.id from (select *from person)h,
(select * from(select *from person)d group by d.email having count(d.email)>1)e where person.email=e.email ));

这里先说一下思路:

这里id 唯一,但email可能重复

1:找到所有重复email,即group by email之后,count(d.email)>1的id

2:由于group by 只能显示多组重复email中的第1组,而我需要挑选所有的组,因此需要根据id,映射到email,然后

找出所有email相同对应的id,即,重复email的所有id。

3:通过min(id)找出每一个不同的email对应的最小id值。

4:2中找到的所有id中,不在3中的id都应当被删除!(即,只保留3中的id)

注意:mysql中,执行删除操作的表与查找的表需要不同,因此在删除的时候需要新建一个派生表进行查找操作

猜你喜欢

转载自blog.csdn.net/hgtjcxy/article/details/81949644