18 May 2018

来自 leetcode 196 的一道数据库题:
https://leetcode-cn.com/problems/delete-duplicate-emails/description/

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+


Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+
delete from Person where Id not in (select min(Id) as Id from Person group by Email);
报错
(1093, u"You can't specify target table 'Person' for update in FROM clause")

意思是不能先 select 出同一表中的某些值,再 update 这个表(在同一语句中) http://www.th7.cn/db/mysql/201506/107949.shtml

修改为

delete from Person where Id not in
    (select Id from
        (select min(Id) as Id from Person group by Email) tmp);