题目描述

(通过次数271,130 | 提交次数342,211,通过率79.23%)

编写一个 SQL 查询,查找?Person 表中所有重复的电子邮箱。
示例:
+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+
| Email   |
+---------+
| a@b.com |
+---------+
说明:所有电子邮箱都是小写字母。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/duplicate-emails
//测试数据
Create table If Not Exists Person (id int, email varchar(255));

insert into Person (id, email) values ('1', 'a@b.com');
insert into Person (id, email) values ('2', 'c@d.com');
insert into Person (id, email) values ('3', 'a@b.com');

解题思路

Person表保存了所有的用户信息,包括用户的Email。
题目要求:查询重复的Email。
重复的Email,是指那些出现次数超过1次的Email。那么,直接统计每个Email出现的次数,然后过滤出次数超过1次的即可。
统计每个Email出现的次数,可以使用GROUP BY+COUNT的方式实现。
而过滤COUNT的结果,SQL提供了HAVING关键字,从而可以节省一层子查询的嵌套。

参考SQL

未特别说明的情况下,参考SQL为基于MySQL8.0实现。
select
    Email
from Person
group by Email
having count(1)>1;
picture loss