Topic
- SQL
Description
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.
Analysis
略
Submission
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
)
Test
略