SQL——查找重复数据/去重

查找重复的电子邮箱

题目来源:力扣182. 查找重复的电子邮箱
要求,编写一个SQL查询查找Person表中所有重复的电子邮箱

Create table If Not Exists Person (Id int, Email varchar(255))
Truncate table Person
insert into Person (Id, Email) values ('1', '[email protected]')
insert into Person (Id, Email) values ('2', '[email protected]')
insert into Person (Id, Email) values ('3', '[email protected]')

在这里插入图片描述
方法一:
使用group by 和辅助表

select Email from
    (select Email,count(Email) as num
    from Person
    group by Email) as statistic
    where num>1;

方法二:group by 和 having条件

select Email 
	from Person
	group by Email
	having(count(Email)>1);

这里需要注意
使用以下语句是错误的,因为 where 子句不能与聚合函数一起使用
它们的执行顺序:where>group by>having>order by,如果where语句与count()一起使用的时候group by 还没有执行,无法使用counting

select Email 
    from Person
	group by Email
    where count(Email)>1;

删除重复电子邮箱

题目来源:力扣196. 删除重复的电子邮箱
编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
在这里插入图片描述
方法一:使用delete+子查询
第一步:对Email进行分组,并将最小的id拿出来
select min(Id) from person group by Email;
第二步:把它保存为一个虚拟表
(select min(Id) from Person group by Email) as need;
第三步:把need表中的id提取出来

select need.id from 
	(select min(Id) as Id
	from Person
	group by Email)
	as need;

第四步:删除不在need中的id中的数据

delete from Person
delete from Person
	where Id 
    not in
	(select need.Id from 
        (
        select min(Id) as Id
        from Person
        group by Email
        )as need
    );

方法二:使用表的自连接

DELETE p1 FROM Person p1,
    Person p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id

这里需要注意的一个是deletezhong使用表的别名:
参考Mysql DELETE 不能使用别名? 是我不会用!
该题目也不可以使用distinct来解决,关于distinct的文章可参考:
SQL中distinct的用法
参考链接
一只猪的解题思路
删除重复的电子邮箱

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章