首页 > 数据库 > 正文

sql 删除表中的重复记录
2017-11-28 23:34:24   来源:   评论:0 点击:

如下sql,找出重复的记录,和重复记录中ID值最小的记录(表中ID为自增长)select MIN(ID) as id, StructSN ,Date,UserID,StarCount,COUNT(StructSN) as cfrom T_Dor_StructStarwhere Date >= '20...
如下sql,找出重复的记录,和重复记录中ID值最小的记录(表中ID为自增长)
 
select MIN(ID) as id, StructSN ,Date,UserID,StarCount,COUNT(StructSN) as c
from T_Dor_StructStar
where Date >= '20160919'
group by StructSN ,Date,UserID,StarCount
having COUNT(StructSN) > 1
 
然后就可以直接删除,基本原理就是,找到重复记录的每一条记录,排除掉重复id最小的记录,删除剩余的重复记录。
 
delete from T_Dor_StructStar
where ID in (
select s.ID from T_Dor_StructStar s,
(
select MIN(ID) as id, StructSN ,Date,UserID,StarCount,COUNT(StructSN) as c
from T_Dor_StructStar
where Date >= '20160919'
group by StructSN ,Date,UserID,StarCount
having COUNT(StructSN) > 1
)a
where
a.Date = s.Date
and a.StructSN = s.StructSN
and a.UserID = s.UserID
and a.StarCount = s.StarCount
and a.id != s.ID

相关热词搜索:sql 删除表中的重复记录

上一篇:使用 WordPress 内置的工具修复和优化数据库
下一篇:最后一页

分享到: 收藏
评论排行