creat table tbl_tmp (select distinct* from tbl);truncate table tbl;//清空表記錄insert into tbl select * from tbl_tmp;//將臨時表中的數據插回來。 這種方法可以實現需求,但是很明顯,對于一個千萬級記錄的表,這種方法很慢,在生產系統中,這會給系統帶來很大的開銷,不可行。
delete from tbl where rowid in (select a.rowid from tbl a, tbl b where a.rowid>b.rowid and a.col1=b.col1 and a.col2 = b.col2) 如果已經知道每條記錄只有一條重復的,這個sql語句適用。但是如果每條記錄的重復記錄有N條,這個N是未知的,就要考慮適用下面這種方法了。
3、利用max或min函數
這里也要使用rowid,與上面不同的是結合max或min函數來實現。SQL語句如下
delete from tbl awhere rowid not in (select max(b.rowid) from tbl b where a.col1=b.col1 and a.col2 = b.col2);//這里max使用min也可以 或者用下面的語句
delete from tbl awhere rowid(select max(b.rowid) from tbl b where a.col1=b.col1 and a.col2 = b.col2);//這里如果把max換成min的話,前面的where子句中需要把""改為">" 跟上面的方法思路基本是一樣的,不過使用了group by,減少了顯性的比較條件,提高效率。SQL語句如下:
deletefrom tbl where rowid not in (select max(rowid) from tbl tgroup by t.col1, t.col2);delete from tbl where (col1, col2) in (select col1,col2 from tblgroup bycol1,col2havingcount(*) >1)and rowidnotin(selectnin(rowid)fromtblgroup bycol1,col2havingcount(*) >1) 還有一種方法,對于表中有重復記錄的記錄比較少的,并且有索引的情況,比較適用。假定col1,col2上有索引,并且tbl表中有重復記錄的記錄比較少,SQL語句如下4、利用group by,提高效率