Oracle快速删除重复的记录[转自青云]

 1做项目的时候,一位同事导数据的时候,不小心把一个表中的数据全都搞重了,也就是说,这个表里所有的记录都有一条重复的。这个表的数据是千万级的,而且是生产系统。也就是说,不能把所有的记录都删除,而且必须快速的把重复记录删掉。
 2
 3对此,总结了一下删除重复记录的方法,以及每种方法的优缺点。
 4
 5为了陈诉方便,假设表名为Tbl,表中有三列col1,col2,col3,其中col1,col2是主键,并且,col1,col2上加了索引。
 6
 71、通过创建临时表
 8
 9可以把数据先导入到一个临时表中,然后删除原表的数据,再把数据导回原表,SQL语句如下:
10
11creat table tbl_tmp (select distinct* from tbl);truncate table tbl;
12            //清空表记录insert into tbl select * from tbl_tmp;//将临时表中的数据插回来。 
13
14这种方法可以实现需求,但是很明显,对于一个千万级记录的表,这种方法很慢,在生产系统中,这会给系统带来很大的开销,不可行。
15
162、利用rowid
17
18在oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的,rowid确定了每条记录是oracle中的哪一个数据文件、块、行上。在重复的记录中,可能所有列的内容都相同,但rowid不会相同。SQL语句如下:
19
20delete from tbl where rowid in (select a.rowid from tbl a,
21            tbl b where a.rowid>b.rowid and a.col1=b.col1 and a.col2 = b.col2)  
22
23如果已经知道每条记录只有一条重复的,这个sql语句适用。但是如果每条记录的重复记录有N条,这个N是未知的,就要考虑适用下面这种方法了。
24
253、利用max或min函数
26
27这里也要使用rowid,与上面不同的是结合max或min函数来实现。SQL语句如下
28
29delete from tbl awhere rowid not in (select max(b.rowid)
30            from tbl b where a.col1=b.col1 and a.col2 = b.col2);
31            //这里max使用min也可以  
32
33或者用下面的语句
34
35delete from tbl awhere rowid<(select max(b.rowid)
36            from tbl b where a.col1=b.col1 and a.col2 = b.col2);
37            //这里如果把max换成min的话,前面的where子句中需要把"<"改为">"  
38
39跟上面的方法思路基本是一样的,不过使用了group by,减少了显性的比较条件,提高效率。SQL语句如下:
40
41deletefrom tbl where rowid not in (select max(rowid)
42            from tbl tgroup by t.col1, t.col2);delete from tbl where (col1, col2)
43            in (select col1,col2 from tblgroup bycol1,col2havingcount(*)
44            >1)and rowidnotin(selectnin(rowid)fromtblgroup bycol1,
45            col2havingcount(*>1)  
46
47还有一种方法,对于表中有重复记录的记录比较少的,并且有索引的情况,比较适用。假定col1,col2上有索引,并且tbl表中有重复记录的记录比较少,SQL语句如下4、利用group by,提高效率 
48 
49
50 
51
52

 1我个人习惯使用:
 23、利用max或min函数
 3这里也要使用rowid,与上面不同的是结合max或min函数来实现。SQL语句如下
 4delete from tbl awhere rowid not in (select max(b.rowid)
 5from tbl b where a.col1=b.col1 and a.col2 = b.col2);
 6//这里max使用min也可以 
 7因为这个方法最简单
 8
 9刚刚发明了一种新写法:
10速度爆快,比上一种快1万倍!!!
11delete from schedule_plan 
12where rowid in (
13select x1 from 
14(
15select rowid as x1, schedule_code,crea_time,
16ROW_NUMBER () over (partition by schedule_code order by crea_time desc) x from schedule_plan)
17where x>1)
18上一种方法需要 300多秒,该方法只要0.29秒。
19
20
posted @ 2008-04-12 20:47  Simmy.卧龙先生  阅读(503)  评论(0编辑  收藏  举报