编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。
示例:
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+
| Email |
+---------+
| a@b.com |
+---------+
说明:所有电子邮箱都是小写字母。
解法一:当数据量过大时,效率较低。时间复杂度O(N^2)
select distinct p1.email as Email from person p1,person p2 where p1.id!=p2.id and p1.email=p2.email;
解法二:使用 count(*) 要比count(字段) 要快,省略了判断字段是否为 null 的过程,mysql 对 count(*) 做了优化。
有关count(1)、count(*)、count(字段)的区别
select distinct email from person group by email having count(*) > 1;
本文介绍了一种在Person表中查找所有重复电子邮箱的SQL查询方法。通过两个不同的解法,展示如何有效地处理大量数据,避免重复记录。解法一采用自连接方式,而解法二则利用group by和count(*)函数进行优化。

1917

被折叠的 条评论
为什么被折叠?



