sql语句如何去重复记录?我们在存储数据的时候,会存在一些重复字段,那么我们如何高效去除重复记录呢?下面给大家分享两种实现方法,感兴趣的朋友可以参考参考。
如果要删除手机(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 )
用临时表插入对500万数据去重(1/2重复)不到10分钟。
其实用删除方式是比较慢的,可能是边找边删除的原因吧,而使用临时表,可以将没有重复的数据ID选出来放在临时表里,再将表的信息按临时表的选择出来的ID,将它们找出来插入到新的表,然后将原表删除,这样就可以快速去重啦。
方法一按照多条件重复处理:
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)