leetcode182 查找重複的電子郵箱 Duplicate Emails

編寫一個 SQL查詢,來查找名爲 Person 的表中的全部重複電子郵件。spa

 

 

 建立表和數據:code

Create table If Not Exists Person (Id int,Email varchar(255));
Truncate table Person;
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');

解法:blog

1.若是一個字段的值在表中重複了,那麼含有重複值的行數必定超過1。 table

group by 對Email分組,那麼Email重複的行個數大於1。class

having 篩選出這些行。效率

select Email
from Person
group by Email
having count(Id) > 1

2.假設表中的字段Id是惟一的,還能夠自鏈接表,選中哪些Id不一樣,Email相同的行。注意投影后要distinct去重。email

select distinct P1.Email
from Person as P1 join Person as P2 on (P1.Id != P2.Id and P1.Email = P2.Email)

3.對每行的Email,子查詢中都在表中查找一次,Email相同的行個數超過1。選中此行。效率低。select

select distinct P1.Email
from Person as P1 
where 1 < (
    select count(*)
    from Person as P2
    where P1.email = P2.email
);

 

 

 

select E1.Name as Employee
from Employee as E1 join Employee as E2 on (E1.ManagerId  = E2.Id and E1.salary > E2.salary)
相關文章
相關標籤/搜索