查询及删除重复记录的 SQL 语句
1、查找表中多余的重复记录,重复记录是根据单个字段(Id)来判断
select * from 表 where Id in (select Id from 表 group byId having count(Id) > 1)
2、删除表中多余的重复记录,重复记录是根据单个字段(Id)来判断,只留有 rowid 最小的记录
DELETE from 表 WHERE (id) IN ( SELECT id FROM 表 GROUP BY id HAVING COUNT(id) > 1) AND ROWID NOT IN (SELECT MIN(ROWID) FROM 表 GROUP BY id HAVING COUNT(*) > 1);
3、查找表中多余的重复记录(多个字段)
select * from 表 a where (a.Id,a.name) in(select Id,namefrom 表 group by Id,name having count(*) > 1)
4、删除表中多余的重复记录(多个字段),只留有 rowid 最小的记录
delete from 表 a where (a.Id,a.name) in (select Id,name from 表 group by Id,name having count(*) > 1) and rowid not in (select min(rowid) from 表 group by Id,name having count(*)>1)
5、查找表中多余的重复记录(多个字段),不包含 rowid 最小的记录
select * from 表 a where (a.Id,a.name) in (select Id,name from 表 group by Id,name having count(*) > 1) and rowid not in (select min(rowid) from 表 group by Id,name having count(*)>1)
例如:
(1)查询部位表的多余的数据 (根据 code )
select count(1) from base_part where code in (select code from base_part group by code having count(code) > 1);
(2)删除多余的数据,只留 rowid 最小的记录
DELETE from base_part WHERE (code) IN ( SELECT code FROM base_part GROUP BY code HAVING COUNT(code) > 1) AND ROWID NOT IN (SELECT MIN(ROWID) FROM base_part GROUP BY code HAVING COUNT(*) > 1);
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于