182. 查找重复的电子邮箱
- 2019 年 10 月 6 日
- 笔记
题目
编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。
示例:
+----+---------+ | Id | Email | +----+---------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+---------+ 根据以上输入,你的查询应返回以下结果: +---------+ | Email | +---------+ | [email protected] | +---------+ 说明:所有电子邮箱都是小写字母。
题解
mysql查看重复数据, 可以按照email进行分组,然后使用having子句过滤count>1的数据,查询的结果就是重复的数据
代码
# 创建表 CREATE TABLE `Person` ( `id` int(11) NOT NULL, `email` varchar(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; # 插入测试数据 insert into Person (id,email) value (1,"[email protected]"); insert into Person (id,email) value (2,"[email protected]"); insert into Person (id,email) value (3,"[email protected]"); # 查找重复数据 select email from Person group by Email having count(email) > 1
运行结果

总结
- 当group by 与聚合函数配合使用时,功能为分组后计算
- 当group by 与 having配合使用时,功能为分组后过滤,获得满足条件的分组的返回结果。
- having与where区别:where过滤行,having过滤组