sql 删除表中多余的重复记录(多个字段),只保留一条记录

来源:互联网 发布:手机淘宝5.4.9.0版本 编辑:程序博客网 时间:2024/04/30 19:14

1.查询重复记录

select * from 表名
where 重复字段 in (select  重复字段 from  表名  group  by 重复字段 having  count(重复字段) > 1)

 

2.删除保留一条重复记录

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

    例子: role表中有两个字段,id,name

             delete from role
              where name   in  (select a.name from  (select  name  from  role group  by  name   having  count(name) > 1) a)
            and id not in (select b.id from(select min(id) id from  role group by name  having count(name)>1) b)