刪除數(shù)據(jù)庫(kù)表中重復(fù)數(shù)據(jù)的總結(jié)(oracle)
這里的重復(fù)數(shù)據(jù)指數(shù)據(jù)庫(kù)中每一列的值都相同的數(shù)據(jù),有時(shí)候也許是沒有主鍵的原因?qū)е聰?shù)據(jù)可能重復(fù),或者是,除了主鍵,其他數(shù)據(jù)重復(fù),那么下面的方法可以都這些重復(fù)數(shù)據(jù)進(jìn)行刪除,保留下重復(fù)數(shù)據(jù)中的一行就可以。
大體可以分為兩個(gè)方法 :一種要用rowid來(lái)進(jìn)行刪除,另外一種,則是用臨時(shí)表來(lái)進(jìn)行刪除。這里講四種方法:
現(xiàn)在假設(shè) 表test中有,三個(gè)列col1,col2,col3;在這樣的表里有很多數(shù)據(jù)是重復(fù)的,現(xiàn)在的目標(biāo)是對(duì)這些數(shù)據(jù)中重復(fù)的數(shù)據(jù)進(jìn)行刪除,保留下的數(shù)據(jù)都是不重復(fù)的。
第一種方法:
Delete from test where rowid not in(select max(rowid) from test group by col1,col2,col3);(覺得最簡(jiǎn)單)
第二種方法:
Delete form test where (col1,col2,col3) in(select col1,col2,col3 from test group bycol1,col2,col3) and rowid not in(select max(rowid) from test group by col1,col2,col3)(跟第一種差不了多少,很常見的思維方式)
這里的刪除適合刪除表中有大量重復(fù)數(shù)據(jù);
第三種方法:
Delete from test a where a.rowid !=(select max(rowid) from test b where a.col1=b.col1and a.col2=b.col2 and a.col3=b.col3)
變形:
Delete from test a where a.rowid<(select max(rowid) from test b where a.col1=b.col1 and a.col2=b.col2 and a.col3=b.col3)
第三種方法適合表中有少量重復(fù)數(shù)據(jù)的表
第四種方法:(臨時(shí)表法)
Create table test2 as select distinct * from test;(建立臨時(shí)表,表中存放不重復(fù)的值)
Truncate table test;(清空原來(lái)的表)
Insert into test select * from test2;(重新插入不重復(fù)的值)
當(dāng)然第四種是比較麻煩的,也適合刪除重復(fù)數(shù)據(jù)比較少的數(shù)據(jù)。
關(guān)于rowid,就是指數(shù)據(jù)庫(kù)表中每一行的標(biāo)示吧,
系統(tǒng)在你插入數(shù)據(jù)的時(shí)候要給每一行的數(shù)據(jù)分配一個(gè)rowid來(lái)進(jìn)行標(biāo)識(shí)每一行,從數(shù)據(jù)插入的那一刻起,rowid 就是定下來(lái)的了。
posted on 2013-08-21 10:34 順其自然EVO 閱讀(341) 評(píng)論(0) 編輯 收藏