难度:简单
编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。 示例:
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+
| Email |
+---------+
| a@b.com |
+---------+
解答
方法一: 看到“查重复”这样的题,首先要用分组函数(group by),再用聚合函数count给email计数直接做判断
select Email
From Person
group by Email
having count(Email
)>=2
方法二: 还有一个使用临时表的方式,稍稍有点麻烦
select Email
, count(Email
) as num
from Person
group by Email
将上表作为临时表,查出不同的email有的个数,然后再判断num>=2所对应的Email 具体sql语句如下:
select Email
from
(
select Email
, count(Email
) as num
from Person
group by Email
) as statistic
where num
>= 1