要求:编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。
表Person:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
+----+------------------+
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | john@example.com |
| 2 | bob@example.com |
+----+------------------+
分析:
1.筛选出需要删除的id,通过where筛选
2.使用delete删除
3.当通过select查询id时,查询到的数据不能直接删除,因为在mysql中,不能先select一个表的记录,再按此条件进行更新和删除同一个表的记录,若直接删除会出现问题
错误的SQL语句:
delete from person where id in (select a.id as id from person a,person b
where a.email=b.email and a.id>b.id);
执行出错:
You can’t specify target table ‘person’ for update in FROM clause
您不能在FROM子句中指定目标表"person"进行更新
4.因此为了解决此问题,我们只要再加上一层select即可
正确的SQL语句:
delete from person where id in(select c.id from
(select a.id as id from person a,person b
where a.email=b.email and a.id>b.id)c);