欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

[LeetCode] 查找重复的电子邮箱

程序员文章站 2023-01-01 11:43:02
编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。 示例 : 根据以上输入,你的查询应返回以下结果: 说明 :所有电子邮箱都是小写字母。 题解: 方法一 :使用 和临时表 算法 重复的电子邮箱存在多次。要计算每封电子邮件的存在次数,我们可以使用以下代码。 以此作为临时表,我们可以得 ......

编写一个 sql 查询,查找 person 表中所有重复的电子邮箱。

示例

+----+---------+
| id | email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+

根据以上输入,你的查询应返回以下结果:

+---------+
| email   |
+---------+
| a@b.com |
+---------+

说明:所有电子邮箱都是小写字母。

题解:

方法一:使用 group by和临时表
算法
重复的电子邮箱存在多次。要计算每封电子邮件的存在次数,我们可以使用以下代码。

select email, count(email) as num
from person
group by email;
| email   | num |
|---------|-----|
| a@b.com | 2   |
| c@d.com | 1   |

以此作为临时表,我们可以得到下面的解决方案。

select email from
(
  select email, count(email) as num
  from person
  group by email
) as statistic
where num > 1;

方法二:使用 group byhaving 条件
group by 添加条件的一种更常用的方法是使用 having 子句,该子句更为简单高效
所以我们可以将上面的解决方案重写为:

select email
    from person
        group by email
            having count(email) > 1;

摘自: