1、题目名称
Duplicate Emails(重复出现的Email)
2、题目地址
https://leetcode.com/problems/duplicate-emails/
3、题目内容
有一个数据表包括Id和Email两列,找出数据表内Email列内容重复出现的Email数据。
例如,现有一个表Person内容如下:
+----+---------+ | Id | Email | +----+---------+ | 1 | [email protected] | | 2 | [email protected] | | 3 | [email protected] | +----+---------+
那么查询得到的结果集为:
+---------+ | Email | +---------+ | [email protected] | +---------+
4、初始化数据库脚本
在MySQL数据库中建立一个名为LEETCODE的数据库,用MySQL命令行中的source命令执行下面脚本:
-- 执行脚本前必须建立名为LEETCODE的DATABASE USE LEETCODE; DROP TABLE IF EXISTS Person; CREATE TABLE Person ( Id INT NOT NULL PRIMARY KEY, Email VARCHAR(50) ); INSERT INTO Person (Id, Email) VALUES (1, ‘[email protected]‘); INSERT INTO Person (Id, Email) VALUES (2, ‘[email protected]‘); INSERT INTO Person (Id, Email) VALUES (3, ‘[email protected]‘); INSERT INTO Person (Id, Email) VALUES (4, ‘[email protected]‘); INSERT INTO Person (Id, Email) VALUES (5, ‘[email protected]‘);
5、解题SQL1
以Email列对数据进行分组,找出所有组内数据数量大于1的Email
SELECT DISTINCT Email FROM Person GROUP BY Email HAVING COUNT(*) > 1
6、解题SQL2
换一个角度考虑,如果两行数据,Id不同,Email相同,则选出这个Email,再对选出的所有Email进行去重。
SELECT DISTINCT A.Email FROM Person AS A, Person AS B WHERE A.Id <> B.Id AND A.Email = B.Email
END
时间: 2024-10-31 10:46:58