LeetCode

天大地大妈咪最大 提交于 2020-12-24 21:19:15

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!