项目场景:
数据库表中添加唯一约束,确保数据准确性
问题描述
表中存在重复数据,导致唯一约束添加失败。清理重复数据保留其中一条
解决方案:
-
查看重复数据
-
查询sql
select a.* from a, ( select UserId, Code, MAX ( Id ) id from a group by UserId, Code having count ( * ) > 1 ) b where a.UserId= b.UserId and a.Code= b.Code and a.id <> b.id
-
删除sql
delete a.* from a, ( select UserId, Code, MAX ( Id ) id from a group by UserId, Code having count ( * ) > 1 ) b where a.UserId= b.UserId and a.Code= b.Code and a.id <> b.id