力扣数据库题目182查找重复的电子邮箱
题目
编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。
示例:
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+
| Email |
+---------+
| a@b.com |
+---------+
说明:所有电子邮箱都是小写字母。
来源:力扣(LeetCode)
方案一
分组
SELECT email
FROM test.person
GROUP BY email
HAVING count(*) > 1
方案二
where子查询
SELECT DISTINCT email
FROM test.person t
WHERE (SELECT count(*) FROM test.person WHERE email = t.email) > 1
方案三
exists判断
SELECT DISTINCT email
FROM test.person t
WHERE EXISTS(SELECT email FROM test.person WHERE email = t.email AND id <> t.id)
方案四
表连接
SELECT DISTINCT a.email
FROM test.person a
INNER JOIN test.person b ON a.email = b.email AND a.id > b.id
总结
一般情况下查询可以先考虑简单查【标准单表查询】,再考虑子查询【SELECT或WHERE子查询】,最后考虑表连接。基本上表连接可以解决几乎所有SQL问题。