当前位置:   article > 正文

LeetCode - Easy - 196. Delete Duplicate Emails

LeetCode - Easy - 196. Delete Duplicate Emails

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 |
+----+------------------+
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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  |
+----+------------------+
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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
)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/799631
推荐阅读
相关标签
  

闽ICP备14008679号