leetcode - 数据库 - 196. 删除重复的电子邮箱 - 为什么delete的时候select报错?

      
      原题:https://leetcode-cn.com/problems/delete-duplicate-emails/
      我自己做leetcode的数据库题目的解题记录:
              解题目录 https://blog.csdn.net/weixin_42845682/article/details/105196004

题目描述

      编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+ 

      例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+ 

      提示:
            执行 SQL 之后,输出是整个 Person 表。
            使用 delete 语句。

答案

第一种答案

答案

delete
from Person 
where id not in( 
select 
	min(p2.id) id  
from person p2 
	group by p2.email 
	having(count(p2.id)>1) 
)

      将重复的邮件的id找出来,然后not in。
      但是后来想了想,最小的不删除,和重复不重复没啥关系啊…于是,就去掉了having:

delete
from Person 
where id not in( 
select 
	min(p2.id) id  
from person p2 
	group by p2.email  
)

      但是执行报错,郁闷。
      后来查了查,需要这样写:

delete
from Person 
where id not in( 
	select id
	from(
		select 
			min(p2.id) id  
		from person p2 
			group by p2.email  
	) tmp
)

      年少无知,不知道为啥…

解惑

      经过问人,是因为:mysql 不能对同一个表进行 update(delete) 和 select 联合操作
      具体情况可以参考:链接地址 https://blog.csdn.net/weixin_42845682/article/details/105449548

第二种答案

      用join其实也可以:

delete 
from person
where id in(
	select id from(
		select
		    p2.id id 
		from person p1
		join person p2 on p1.email=p2.email 
		where p2.id>p1.id
	) tmp
)

第三种答案

      这个答案我没想出来,我也没想到还能这么写…

DELETE p1 FROM Person p1,
    Person p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id 

      我还是太年轻…
      

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