oracle 快速删除重复的记录
oracle-快速删除重复的记录
做项目的时候,一位同事导数据的时候,不小心把一个表中的数据全都搞重了,也就是说,这个表里所有的记录都有一条重复的。这个表的数据是千万级的,而且是生产系统。也就是说,不能把所有的记录都删除,而且必须快速的把重复记录删掉。
对此,总结了一下删除重复记录的方法,以及每种方法的优缺点。
为了陈诉方便,假设表名为Tbl,表中有三列col1,col2,col3,其中col1,col2是主键,并且,col1,col2上加了索引。
1、通过创建临时表
可以把数据先导入到一个临时表中,然后删除原表的数据,再把数据导回原表,SQL语句如下:
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)
delete from tbl a where 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 a where rowid < (select max(b.rowid) from tbl b where a.col1=b.col1 and a.col2 = b.col2);//这里如果把max换成min的话,前面的where子句中需要把"<"改为">"
delete from tbl where rowid not in (select max(rowid) from tbl t group by t.col1, t.col2 );delete from tbl where (col1, col2) in (select col1,col2 from tbl group by col1,col2 having count(*) > 1) and rowid not in (select nin(rowid) from tbl group by col1,col2 having count(*) > 1)