本来要删除error_barcode表中barcode值重复的只保留一条
表结构如下(PS:id是自增长,该图是删除成功所以id不连续)
sql语句如下:
DELETE FROM error_barcode WHERE barCode IN ( SELECT barCode FROM error_barcode GROUP BY barCode HAVING count(barCode) > 1 ) AND id NOT IN ( SELECT min(id) FROM error_barcode GROUP BY barCode HAVING count(barCode) > 1 )
但是却报错误
上网查找了下,这是MySql的一个问题,就是不能再同一个语句里对同一张表先select某些值在update,
那就需要把子查询在放入一个子查询中
DELETE from error_barcode WHERE barCode in( select a.barCode from(select * from error_barcode)a GROUP BY barCode having count(barCode)>1 )and id not in ( select min(id) from(select * from error_barcode)b GROUP BY barCode having count(barCode)>1 )
可以看到我把下面两个子查询
SELECT barCode FROM error_barcode GROUP BY barCode HAVING count(barCode) > 1
SELECT min(id) FROM error_barcode GROUP BY barCode HAVING count(barCode) > 1
改成
select a.barCode from(select * from error_barcode)a GROUP BY barCode having count(barCode)>1
select min(id) from(select * from error_barcode)b GROUP BY barCode having count(barCode)>1
就行了
原文地址:https://www.cnblogs.com/xudongxuIT/p/8831977.html
时间: 2024-11-08 06:59:15