LeetCode force buckle brush title database (182): find duplicate e-mail

topic

Write a SQL query to find all duplicate Person table e-mail.

Example:

Here Insert Picture Description

Based on the above inputs, your query should return the following results:

Here Insert Picture Description
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;
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;

Here Insert Picture Description

2. Since the two connection tables

SELECT
	* 
FROM
	person AS a,
	person AS b;

Here Insert Picture Description

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;

Here Insert Picture Description

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;

related business

Here Insert Picture Description

Published 516 original articles · won praise 640 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_35456045/article/details/104472515