LeetCode 196. Delete Duplicate Emails (sql)

196. Delete Duplicate Emails

Easy

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 from Person where id not in( 
    select t.id from (
        select min(id) as id from Person group by email
    ) t
)

评论

MySQL不允许DELETE的WHERE从句中查询被DELETE的表,但是可以通过嵌套一层SELECT的方式规避这个问题

上一篇:Nginx安装启动shell脚本


下一篇:完全卸载删除gitlab