数据库
首页 > 数据库> > LeetCode 196. Delete Duplicate Emails (sql)

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的方式规避这个问题

标签:196,example,Person,Duplicate,id,table,Id,com,LeetCode
来源: https://blog.csdn.net/da_kao_la/article/details/99696380