收藏文章 楼主

MySQL中查询、删除重复记录的方法大全

版块:数据库存储过程   类型:普通   作者:小绿叶技术博客   查看:1926   回复:1   获赞:0   时间:2021-01-26 15:37:53


select * from zyj_dxzxyh where name in (select name from zyj_dxzxyh group by name having count(name) > 1)

# 查找表中多余的重复记录

# 选择 * 所有列 从表zyj_dxzxyh 

# where 条件过滤  name 列 是字句

# 字句:选择name列   group by 分组排序列 name ;  having count(name) 计数 name列相同的行的个是大于1 



delete from people where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1) and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)

# 删除表中多余的重复记录


select * from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)

# 查找表中多余的重复记录


delete from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

# 删除表中多余的重复记录(多个字段),只留有rowid最小的记录

select * from vitae a where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1)

# 查找表中多余的重复记录(多个字段),不包含rowid最小的记录




#-------------------------------------- 补充 -------------------------------------- 

select distinct * from tableName

就可以得到无重复记录的结果集。

如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除



select distinct * into #Tmp from tableName

drop table tableName

select * into tableName from #Tmp

drop table #Tmp

发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。


2、这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下

假设有重复的字段为Name,Address,要求得到这两个字段唯一的结果集



select identity(int,1,1) as autoID, * into #Tmp from tableName

select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoID

select * from #Tmp where autoID in(select autoID from #tmp2)


提供企业建站服务,免费网防系统,提交信息登录 http://yundun.ddoss.cn 邮箱: proposal@ddoss.cn 
回复列表
默认   热门   正序   倒序

回复:MySQL中查询、删除重复记录的方法大全

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息