刪除數據庫表中重復數據的總結(oracle)
這里的重復數據指數據庫中每一列的值都相同的數據,有時候也許是沒有主鍵的原因導致數據可能重復,或者是,除了主鍵,其他數據重復,那么下面的方法可以都這些重復數據進行刪除,保留下重復數據中的一行就可以。
大體可以分為兩個方法 :一種要用rowid來進行刪除,另外一種,則是用臨時表來進行刪除。這里講四種方法:
現在假設 表test中有,三個列col1,col2,col3;在這樣的表里有很多數據是重復的,現在的目標是對這些數據中重復的數據進行刪除,保留下的數據都是不重復的。
第一種方法:
Delete from test where rowid not in(select max(rowid) from test group by col1,col2,col3);(覺得最簡單)
第二種方法:
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)(跟第一種差不了多少,很常見的思維方式)
這里的刪除適合刪除表中有大量重復數據;
第三種方法:
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)
第三種方法適合表中有少量重復數據的表
第四種方法:(臨時表法)
Create table test2 as select distinct * from test;(建立臨時表,表中存放不重復的值)
Truncate table test;(清空原來的表)
Insert into test select * from test2;(重新插入不重復的值)
當然第四種是比較麻煩的,也適合刪除重復數據比較少的數據。
關于rowid,就是指數據庫表中每一行的標示吧,
系統在你插入數據的時候要給每一行的數據分配一個rowid來進行標識每一行,從數據插入的那一刻起,rowid 就是定下來的了。