您的位置:首页 > 数据库 > Oracle

oracle-快速删除重复的记录

2006-07-20 11:15 453 查看
假设表名为Tbl,表中有三列col1,col2,col3,无主键。

1、通过创建临时表

可以把数据先导入到一个临时表中,然后删除原表的数据,再把数据导回原表,SQL语句如下:

creat table tbl_tmp (select distinct* from tbl);

truncate table tbl;//清空表记录

insert into tbl select * from tbl_tmp;//将临时表中的数据插回来。

2、利用rowid

在oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的。SQL语句如下:

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函数

SQL语句如下

delete from tbl a where rowid exists (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子句中需要把"<"改为">"

4、利用group by,提高效率

跟上面的方法思路基本是一样的,不过使用了group by,减少了显性的比较条件,提高效率。SQL语句如下:

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 exists (select nin(rowid) from tbl group by col1,col2 having count(*) > 1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: