Fork me on GitHub

leetcode-for-sql-查找重复的电子邮箱

LeetCode-182-查找重复的电子邮箱

本文讲解的是LeetCode-SQL的第182题目,题目名为:查找重复的电子邮箱。

难易程度:简单,做完发现是真的简单。

题目

下面是具体的题目:从给定的表Person中找出重复的电子邮箱

思路

个人方法1

根据每个邮箱Email进行分组统计,当统计的个数大于1,则表示该邮箱是重复的。同样代码运行两次,差别尽然这么大!

1
2
3
4
5
select
Email
from Person
group by Email
having count(Email) > 1; -- 过滤条件

个人方法2

方法2的思路和方法1是类似的,只是使用一个中间结果表,最后通过where条件来过滤;方法1使用的having条件来过滤:

1
2
3
4
5
6
7
8
9
select
t.Email
from(select -- 统计每个Email的个数
Email
,count(*) as number -- 个数
from Person
group by Email
)t -- 临时结果表
where t.number > 1; -- 选择个数大于1的Email

临时结果表t的效果:

参考方法

将给定的表进行自连接,连接的条件是:邮箱相同,但是Id号不同:

1
2
3
4
select
distinct (p1.Email) -- 去重统计邮箱
from Person p1
join Person p2 on p1.Email = p2.Email and p1.Id != p2.Id; -- 指定连接条件

本文标题:leetcode-for-sql-查找重复的电子邮箱

发布时间:2021年06月07日 - 20:06

原始链接:http://www.renpeter.cn/2021/06/07/leetcode-for-sql-%E6%9F%A5%E6%89%BE%E9%87%8D%E5%A4%8D%E7%9A%84%E7%94%B5%E5%AD%90%E9%82%AE%E7%AE%B1.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea