利用SQL语句怎么删除重复的记录

54次阅读
没有评论

共计 2135 个字符,预计需要花费 6 分钟才能阅读完成。

自动写代码机器人,免费开通

利用 SQL 语句怎么删除重复的记录?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面丸趣 TV 小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

如果要删除手机 (mobilePhone),电话(officePhone),邮件(email) 同时都相同的数据,以前一直使用这条语句进行去重:

delete from  表  where id not in 
(select max(id) from  表  group by mobilePhone,officePhone,email ) 
or 
delete from  表  where id not in 
 (select min(id) from  表  group by mobilePhone,officePhone,email ) 
delete from  表  where id not in 
(select max(id) from  表  group by mobilePhone,officePhone,email ) 
or 
delete from  表  where id not in 
 (select min(id) from  表  group by mobilePhone,officePhone,email )

其中下面这条会稍快些。上面这条数据对于 100 万以内的数据效率还可以,重复数 1 / 5 的情况下几分钟到几十分钟不等,但是如果数据量达到 300 万以上,效率骤降,如果重复数据再多点的话,常常会几十小时跑不完,有时候会锁表跑一夜都跑不完。无奈只得重新寻找新的可行方法,今天终于有所收获:

// 查询出唯一数据的 ID, 并把他们导入临时表 tmp 中  
select min(id) as mid into tmp from  表  group by mobilePhone,officePhone,email 
 // 查询出去重后的数据并插入 finally 表中  
insert into finally select (除 ID 以外的字段) from customers_1 where id in (select mid from tmp) 
// 查询出唯一数据的 ID, 并把他们导入临时表 tmp 中  
select min(id) as mid into tmp from  表  group by mobilePhone,officePhone,email 
 // 查询出去重后的数据并插入 finally 表中  
insert into finally select (除 ID 以外的字段) from customers_1 where id in (select mid from tmp)

效率对比:用 delete 方法对 500 万数据去重(1/ 2 重复)约 4 小时。4 小时,很长的时间。

用临时表插入对 500 万数据去重(1/ 2 重复)不到 10 分钟。

其实用删除方式是比较慢的,可能是边找边删除的原因吧,而使用临时表,可以将没有重复的数据 ID 选出来放在临时表里,再将表的信息按临时表的选择出来的 ID,将它们找出来插入到新的表,然后将原表删除,这样就可以快速去重啦。

SQL 语句去掉重复记录,获取重复记录

按照某几个字段名称查找表中存在这几个字段的重复数据并按照插入的时间先后进行删除,条件取决于 order by 和 row_num。

方法一按照多条件重复处理:

delete tmp from( 
select row_num = row_number() over(partition by  字段,字段  order by  时间  desc) 
 from  表  where  时间  getdate()-1 
 ) tmp 
 where row_num   1 
delete tmp from( 
select row_num = row_number() over(partition by  字段,字段  order by  时间  desc) 
 from  表  where  时间  getdate()-1 
 ) tmp 
 where row_num   1

方法二按照单一条件进行去重:

delete from  表  where  主键 ID not in( 
select max(主键 ID) from  表  group by  需要去重的字段  having count(需要去重的字段) =1 
 ) 
delete from  表  where  主键 ID not in( 
select max(主键 ID) from  表  group by  需要去重的字段  having count(需要去重的字段) =1 
 )

注意:为提高效率如上两个方法都可以使用临时表,not in 中的表可以先提取临时表 #tmp,

然后采用 not exists 来执行,为避免数量过大,可批量用 Top 控制删除量

delete top(2) from  表  
 where not exists (select  主键 ID 
 from #tmp where #tmp. 主键 ID= 表. 主键 ID)

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注丸趣 TV 行业资讯频道,感谢您对丸趣 TV 的支持。

向 AI 问一下细节

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-04发表,共计2135字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)