【力扣日记】【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%的用户

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