赞
踩
https://leetcode.com/problems/delete-duplicate-emails/
Write a SQL query to delete all duplicate email entries in a table named Person
, keeping only unique emails based on its smallest Id.
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person
table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
Note:
Your output is the whole Person
table after executing your sql. Use delete
statement.
略
DELETE p FROM Person p, Person q WHERE p.Id>q.Id AND q.Email=p.Email
------------------------------------------------------------------------
-- this clause doesn't word in mysql
-- DELETE FROM Person WHERE id NOT IN(SELECT min(id) AS id FROM Person GROUP BY email)
--
-- you will be noted " You can't specify target table 'Person' for update in FROM clause ",
-- The solution is using a middle table with select clause:
DELETE FROM Person WHERE id NOT IN(
SELECT t.id FROM (
SELECT min(id) AS id FROM Person GROUP BY email
) t
)
略
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。