sql删除重复记录只保留一条

SQL语句
338
0
0
2022-04-13

查询重复记录

select 字段名 from 表名 where 字段名 in (select 字段名  from 表名 group by 字段名  having count(1) >= 2
) ORDER BY  字段名

查询出所有重复记录并且删除多余的只保留一条

delete from 表名
where 
重复字段名 in (SELECT a.重复字段名from(select 重复字段名
    from 表名
    group by 重复字段名 having count(1) > 1) a
)
and 
id(只保留id最小的一个) not in (
SELECT b.id from(select min(id) as id
    from 表名 
    group by 重复字段名 having count(1)>1) b
)