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