查找重複的電子郵箱
題目來源:力扣182. 查找重複的電子郵箱
要求,編寫一個SQL查詢查找Person表中所有重複的電子郵箱
Create table If Not Exists Person (Id int, Email varchar(255))
Truncate table Person
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]')
方法一:
使用group by 和輔助表
select Email from
(select Email,count(Email) as num
from Person
group by Email) as statistic
where num>1;
方法二:group by 和 having條件
select Email
from Person
group by Email
having(count(Email)>1);
這裏需要注意
使用以下語句是錯誤的,因爲 where 子句不能與聚合函數一起使用。
它們的執行順序:where>group by>having>order by,如果where語句與count()一起使用的時候group by 還沒有執行,無法使用counting
select Email
from Person
group by Email
where count(Email)>1;
刪除重複電子郵箱
題目來源:力扣196. 刪除重複的電子郵箱
編寫一個 SQL 查詢,來刪除 Person 表中所有重複的電子郵箱,重複的郵箱裏只保留 Id 最小 的那個。
方法一:使用delete+子查詢
第一步:對Email進行分組,並將最小的id拿出來
select min(Id) from person group by Email;
第二步:把它保存爲一個虛擬表
(select min(Id) from Person group by Email) as need;
第三步:把need表中的id提取出來
select need.id from
(select min(Id) as Id
from Person
group by Email)
as need;
第四步:刪除不在need中的id中的數據
delete from Person
delete from Person
where Id
not in
(select need.Id from
(
select min(Id) as Id
from Person
group by Email
)as need
);
方法二:使用表的自連接
DELETE p1 FROM Person p1,
Person p2
WHERE
p1.Email = p2.Email AND p1.Id > p2.Id
這裏需要注意的一個是deletezhong使用表的別名:
參考Mysql DELETE 不能使用別名? 是我不會用!
該題目也不可以使用distinct來解決,關於distinct的文章可參考:
SQL中distinct的用法
參考鏈接
一隻豬的解題思路
刪除重複的電子郵箱