MySql删除重复只保留一条
Posted xudongxuit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySql删除重复只保留一条相关的知识,希望对你有一定的参考价值。
本来要删除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
就行了
以上是关于MySql删除重复只保留一条的主要内容,如果未能解决你的问题,请参考以下文章