GuilinDev

Lc0196

05 August 2008

196 Delete Duplicate Emails

Write a SQL query to delete all duplicate email entries in a table named

1
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

1
Person
table should have the following rows:

1
2
3
4
5
6
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

Note:

Your output is the whole

1
Person
table after executing your sql. Use
1
delete
statement.

Schema

1
2
3
4
Truncate table Person
insert into Person (Id, Email) values ('1', 'john@example.com')
insert into Person (Id, Email) values ('2', 'bob@example.com')
insert into Person (Id, Email) values ('3', 'john@example.com')

Solution

找到出现次数为1的emails,剩下的删掉

1
2
3
4
5
6
7
8
# Write your MySQL query statement below
Delete from Person Where Id not in (
    Select tmp.Id from (
        Select min(Id) as Id 
        from Person 
            Group By email
    ) tmp
)