【力扣日記】【MySQL】182 查找重複的電子郵箱 196 刪除重複的電子郵箱

示例:
+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+
根據以上輸入,你的查詢應返回以下結果:
+---------+
| Email   |
+---------+
| a@b.com |
+---------+
說明:所有電子郵箱都是小寫字母。

算法

內連接

select distinct P.Email from Person P inner join Person P2 on p.Email=P2.Email and p.id!=p2.id

執行用時 :182 ms, 在所有 MySQL 提交中擊敗了48.26%的用戶
內存消耗 :0B, 在所有 MySQL 提交中擊敗了100.00%的用戶

自連接

select distinct P.Email from Person P, Person P2 where p.Email=P2.Email and p.id!=p2.id

執行用時 :193 ms, 在所有 MySQL 提交中擊敗了40.90%的用戶

196 刪除重複的電子郵箱

delete from Person where Id in (select a.Id from Person a, Person b where a.Email=b.Email and  a.Id>b.Id);

MySql報錯: You can’t specify target table ‘table name’ for update in FROM clause
錯誤提示:不能在同一語句中select出表中的某些值,再update這個表。

解決方法
方案1:

delete from Person where Id in (select Id from (select a.Id from Person a, Person b where a.Email=b.Email and  a.Id>b.Id) t)

原理是把第一遍的查詢結果作爲新表t在使用,規避了錯誤

執行用時 :560 ms, 在所有 MySQL 提交中擊敗了83.03%的用戶
內存消耗 :0B, 在所有 MySQL 提交中擊敗了100.00%的用戶

方案2:
先將第一遍的查詢結果保存到新表,然後根據新表進行刪除操作,最後刪除臨時表

create table tp select a.Id from Person a, Person b where a.Email=b.Email and  a.Id>b.Id;
delete from Person where Id in (select * from tp);
drop table tp;

執行用時 :737 ms, 在所有 MySQL 提交中擊敗了62.72%的用戶
內存消耗 :0B, 在所有 MySQL 提交中擊敗了100.00%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章