【Leetcode】Delete Duplicate Emails 话说MySQLFROM子句

原文链接: https://my.oschina.net/comeon001/blog/732393

【Leetcode】Delete Duplicate Emails[1] Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.

(删除Person表中重复邮箱的记录,保留最小号标记的邮箱Id与Email)

解题思路:任务拆分-SQL组合-SQL优化

题目任务可以分为两大任务——1)筛选出最小Id的重复记录 2)删除重复数据中Id不在最小集合的记录。 对于任务1),SQL语句可以写为

SELECT min(Id) FROM Person GROUP BY Email HAVING COUNT(*)>1

结合任务1),对于任务2),SQL语句可以写成

DELETE FROM Person WHERE Id NOT IN (SELECT min(Id) FROM Person GROUP BY Email HAVING COUNT(*)>1).

但Leetcode会报错:

Runtime Error Message:
Line 3: SyntaxError: near 'GROUP BY Email
WHERE Id not in (SELECT min(Id) FROM Person GROUP BY Email HAVIN'
Last executed input:
{"headers": {"Person": ["Id"
"Email"]}
"rows": {"Person": []}}

查阅资料[2]:"有些数据库需要用from关键字,但是MySQL允许对表达式求值而不引用任何表",[3]:"在MySQL中,禁止在FROM子句中指定被更新的目标表。",知道在MySQL的FROM子句中不能采用更新表。因此,在任务2)中加入SELECT子查询,将任务2)筛选出的记录结果定义为一个名为t的表,在t表中再进行任务1)的删除操作。 注意:

(SELECT min(Id) FROM Person GROUP BY Email) as  t

必须要保证重命名为一个新表,否则依然报错,原理同上。

DELETE FROM Person
WHERE Id not in 
(SELECT * FROM (SELECT min(Id) FROM Person GROUP BY Email) as  t);

Ref. [1] https://leetcode.com/problems/delete-duplicate-emails/

[2] https://www.zybuluo.com/Belinda/note/979941.

[3] http://bookshadow.com/weblog/2015/03/29/leetcode-delete-duplicate-emails/

转载于:https://my.oschina.net/comeon001/blog/732393

你可能感兴趣的:(【Leetcode】Delete Duplicate Emails 话说MySQLFROM子句)