Article Directory
topic
Write a SQL query to find all duplicate Person table e-mail.
Example:
Based on the above inputs, your query should return the following results:
Note: All e-mail all lowercase letters.
analysis
Method One: Use GROUP BY and temporary tables
Algorithms
exist repeated e-mail. To calculate the number of the existence of each email, we can use the following code.
MySQL
select Email, count(Email) as num
from Person
group by Email;
on one | |
---|---|
[email protected] | 2 |
[email protected] | 1 |
As a temporary table, we get the following solutions.
MySQL
select Email from
(
select Email, count(Email) as num
from Person
group by Email
) as statistic
where num > 1
;
Method Two: Use GROUP BY and HAVING conditions
GROUP BY to add one kind of the condition of the more common method is to use a HAVING clause, which is more simple and efficient.
So we can rewrite the above solutions are:
MySQL
select Email
from Person
group by Email
having count(Email) > 1;
Method three: Since the connection
1. View the table
SELECT
*
FROM
person;
2. Since the two connection tables
SELECT
*
FROM
person AS a,
person AS b;
The final result 3
SELECT DISTINCT
a.Email AS Email
FROM
person AS a,
person AS b
WHERE
a.Id < b.Id
AND a.Email = b.Email;
answer
The first
select Email from
(
select Email, count(Email) as num
from Person
group by Email
) as statistic
where num > 1
;
The second
select Email
from Person
group by Email
having count(Email) > 1;
The third
SELECT DISTINCT
a.Email AS Email
FROM
person AS a,
person AS b
WHERE
a.Id < b.Id
AND a.Email = b.Email;