MySQL查找重复的电子邮箱

Posted willem_chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL查找重复的电子邮箱相关的知识,希望对你有一定的参考价值。

SQL架构

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');

题目描述

编写一个 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 |
+---------+-----+
2 rows in set (0.00 sec)

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

select Email from
(
  select Email, count(Email) as num
  from Person
  group by Email
) as statistic
where num > 1;

+---------+
| Email   |
+---------+
| a@b.com |
+---------+
1 row in set (0.00 sec)

方法二:使用 GROUP BY 和 HAVING 条件

向 GROUP BY 添加条件的一种更常用的方法是使用 HAVING 子句,该子句更为简单高效。

所以我们可以将上面的解决方案重写为:

select Email
from Person
group by Email
having count(Email) > 1;
+---------+
| Email   |
+---------+
| a@b.com |
+---------+
1 row in set (0.00 sec)

以上是关于MySQL查找重复的电子邮箱的主要内容,如果未能解决你的问题,请参考以下文章

使用正则表达式python查找电子邮件[重复]

如何创建片段以重复变量编号中的代码行

MySQL 练习<3>

MySQL 练习<3>

182. 查找重复的电子邮箱

linux中怎么查看mysql数据库版本