案例
需求
有一个汽车表,字段有id主键、name、color、price。现需要删除car表中颜色color字段的重复数据,只保留最小的id数据。
实现
错误SQL语句:
delete from car
where color in
(select color from car GROUP BY color HAVING COUNT(color)>1)
and id not in
(select min(id) from car GROUP BY color HAVING count(color)>1)
错误原因: You can't specify target table for delete in FROM car,因为在删除这个表和数据时又查询了它,而查询的数据又做了删除的条件。
解决办法:把要删除的几列数据的查询结果做为一个第三方表,然后筛选更新。
正确SQL语句:
delete from car
where color in
(select c.color from
(select color from car GROUP BY color HAVING COUNT(color)>1) c)
and id not in
(select i.mid from
(select min(id) as mid from car GROUP BY color HAVING count(color)>1) i)
分析
整体步骤分为三步:
- 查询要删除的重复字段信息
- 查询要删除的重复字段的id(只保留最小id)
- 执行删除操作
1.查询重复数据
既然要删除重复数据,我得先找到指定字段数据的重复次数大于1的所有的重复字段数据(等于1的则不算重复数据)。
select c.color from (select color from car GROUP BY color HAVING COUNT(color)>1) c。
2.查询最小id之外的id
找到重复字段数据的id信息,排除其中最小的id。可以先找到对应重复字段的最小id,然后使用not in排除掉。
select i.mid from (select min(id) as mid from car GROUP BY color HAVING count(color)>1) i)。
3.执行删除操作。