当我们的测试环境运行一段时间后总会产生一些垃圾数据,你见或不见, 他就在那里, 不悲不喜;直到某一天你在测试某段代码时发现他影响到了你,你决定把这些垃圾数据删除,下面我来和大家一起看如何删除这些重复数据。

1.查询出所有要删除的数据

select 重复字段名称,count(*) from 表名 group by 重复字段名称 having count(*) > 1; 

2.查询出待删除的数据的最小id

select 重复字段名称,min(id) from 表名
where 重复字段名称 in
  (select 重复字段名称 from (select 重复字段名称,count(*) from 表名 group by 重复字段名称 having count(*) > 1))
group by 重复字段名称;

3.删除数据

delete from 表名 
where 重复字段名称 in 
  (select 重复字段名称 from 
     (select 重复字段名称,count(*) from 表名 group by 重复字段名称 having count(*) > 1))
and id not in 
  (select id from (select 重复字段名称,min(id) id from 表名 where 重复字段名称 in
    (select 重复字段名称 from (select 重复字段名称,count(*) from 表名 group by 重复字段名称 having count(*) > 1))
  group by 重复字段名称))

Logo

更多推荐