Sqlserver - 去重

如果要删除手机(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)

 

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

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


你可能感兴趣的:(SQLSERVER,数据库优化)