面试题:删除重复的Email记录

难度:容易

写一段SQL语句,从表Person中删除所有重复的email记录,只保留最小Id的那条记录。

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id是主键。

例如:执行SQL语句后,上表Person应该只剩下如下记录:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

 

答案:

DELETE FROM Person WHERE Id in (
    SELECT c.Id FROM(
        SELECT a.Id FROM Person a, Person b WHERE a.id > b.id AND a.Email= b.Email
    )c
)

 

posted @ 2015-08-26 20:00  -小城-  阅读(213)  评论(0编辑  收藏  举报