海量數(shù)據(jù)(百萬以上),其中有些全部字段都相同,有些部分字段相同,怎樣高效去除重復(fù)?
如果要刪除手機(mobilePhone),電話(officePhone),郵件(email)同時都相同的數(shù)據(jù),以前一直使用這條語句進(jìn)行去重:
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 )
其中下面這條會稍快些。上面這條數(shù)據(jù)對于100萬以內(nèi)的數(shù)據(jù)效率還可以,重復(fù)數(shù)1/5的情況下幾分鐘到幾十分鐘不等,但是如果數(shù)據(jù)量達(dá)到300萬以上,效率驟降,如果重復(fù)數(shù)據(jù)再多點的話,常常會幾十小時跑不完,有時候會鎖表跑一夜都跑不完。無奈只得重新尋找新的可行方法,今天終于有所收獲:
//查詢出唯一數(shù)據(jù)的ID,并把他們導(dǎo)入臨時表tmp中
select
min
(id)
as
mid
into
tmp
from
表
group
by
mobilePhone,officePhone,email
//查詢出去重后的數(shù)據(jù)并插入finally表中
insert
into
finally
select
(除ID以外的字段)
from
customers_1
where
id
in
(
select
mid
from
tmp)
//查詢出唯一數(shù)據(jù)的ID,并把他們導(dǎo)入臨時表tmp中
select
min
(id)
as
mid
into
tmp
from
表
group
by
mobilePhone,officePhone,email
//查詢出去重后的數(shù)據(jù)并插入finally表中
insert
into
finally
select
(除ID以外的字段)
from
customers_1
where
id
in
(
select
mid
from
tmp)
效率對比:用delete方法對500萬數(shù)據(jù)去重(1/2重復(fù))約4小時。4小時,很長的時間。
用臨時表插入對500萬數(shù)據(jù)去重(1/2重復(fù))不到10分鐘。
其實用刪除方式是比較慢的,可能是邊找邊刪除的原因吧,而使用臨時表,可以將沒有重復(fù)的數(shù)據(jù)ID選出來放在臨時表里,再將表的信息按臨時表的選擇出來的ID,將它們找出來插入到新的表,然后將原表刪除,這樣就可以快速去重啦。
SQL語句去掉重復(fù)記錄,獲取重復(fù)記錄
按照某幾個字段名稱查找表中存在這幾個字段的重復(fù)數(shù)據(jù)并按照插入的時間先后進(jìn)行刪除,條件取決于order by 和row_num。
方法一按照多條件重復(fù)處理:
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
方法二按照單一條件進(jìn)行去重:
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來執(zhí)行,為避免數(shù)量過大,可批量用Top控制刪除量
delete
top
(2)
from
表
where
not
exists (
select
主鍵ID
from
#tmp
where
#tmp.主鍵ID=表.主鍵ID)
總結(jié)
以上所述是小編給大家介紹的使用SQL語句去掉重復(fù)的記錄,希望對大家有所幫助,
- SQL server數(shù)據(jù)庫高可用日志傳送的方法
- Sql Server 數(shù)據(jù)庫中調(diào)用dll文件的過程
- Sql Server 數(shù)據(jù)庫獲取字符串中小寫字母的SQL語句
- Sql Server數(shù)據(jù)庫如何去掉內(nèi)容里面的Html標(biāo)簽
- SQL Server數(shù)據(jù)庫遠(yuǎn)程更新目標(biāo)表數(shù)據(jù)的存儲過程
- MsSql 數(shù)據(jù)庫使用sqlplus創(chuàng)建DDL和DML操作方法
- SQL語句中不同的連接JOIN及SQL中join的各種用法
- SQL SERVER 2012數(shù)據(jù)庫自動備份的方法
- SQL Server數(shù)據(jù)庫調(diào)整表中列的順序操作方法及遇到問題
- 利用數(shù)據(jù)庫trigger對安全進(jìn)行監(jiān)控