描述
Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.
1 2 3 4 5 6 7 8 +----+------------------+ | 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:
1 2 3 4 5 6 +----+------------------+ | Id | Email | +----+------------------+ | 1 | john@example.com | | 2 | bob@example.com | +----+------------------+
分析
大意是删掉 Emails 表中 Email 重复的部分,留下 Id 最小的行
解决方案(MySQL)
1 2 3 4 5 6 7 # Write your MySQL query statement below DELETE FROM Person WHERE Id not in (SELECT Id FROM (SELECT min(Id) as Id FROM Person p GROUP BY p.Email) as tmp_table )