likes
comments
collection
share

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

作者站长头像
站长
· 阅读数 53

公众号:尤而小屋作者:Peter编辑:Peter

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

大家好,我是Peter~

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

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

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

题目

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

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

思路

个人方法1

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

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

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

个人方法2

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

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

临时结果表t的效果:

LeetCode-SQL-182-查找重复的电子邮箱LeetCode-182-查找重复的电子邮箱 大家好,我是Peter

参考方法

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

select 
    distinct (p1.Email)  -- 去重统计邮箱
from Person p1
join Person p2 on p1.Email = p2.Email and p1.Id != p2.Id;  -- 指定连接条件
转载自:https://juejin.cn/post/6971599102941347870
评论
请登录