Sql去重语句

 

海量数据(百万以上),其中有些所有字段都相同,有些部分字段相同,怎样高效去除重复?html

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

delete fromwhere id not in
(select max(id) fromgroup by mobilePhone,officePhone,email )
or
delete fromwhere id not in
(select min(id) fromgroup by mobilePhone,officePhone,email )

 

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

//查询出惟一数据的ID,并把他们导入临时表tmp中
select min(id) as mid into tmp fromgroup 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小时,很长的时间。htm

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

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

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

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

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

 

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

delete fromwhere 主键ID not in(
  select max(主键ID) fromgroup by 须要去重的字段 having count(须要去重的字段)>=1
)

 

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

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

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

 

 

 

 

-------------------->>>

相关文章
相关标签/搜索