ROWID的使用——快速删除重复的记录

ROWID是数据的详细地址,通过rowid,oracle可以快速的定位某行具体的数据的位置。
ROWID可以分为物理rowid和逻辑rowid两种。普通的表中的rowid是物理rowid,索引组织表(IOT)的rowid是逻辑rowid。

当表中有大量重复数据时,可以使用ROWID快速删除重复的记录。

举例:
--建表tbl
SQL> create table stu(no number,name varchar2(10),sex char(2));
--添加测试记录
SQL> insert into stu values(1, 'ab',’男’);
SQL> insert into stu values(1, 'bb',’女’);
SQL> insert into stu values(1, 'ab',’男’);
SQL> insert into stu values(1, 'ab',’男’);
SQL>commit;

删除重复记录方法很多,列出两种。

⑴ 通过创建临时表

可以把数据先导入到一个临时表中,然后删除原表的数据,再把数据导回原表,SQL语句如下:
SQL>create table stu_tmp as select distinct* from stu;
SQL>truncate table sut; //清空表记录
SQL>insert into stu select * from stu_tmp; //将临时表中的数据添加回原表

这种方法可以实现需求,但是很明显,对于一个千万级记录的表,这种方法很慢,在生产系统中,这会给系统带来很大的开销,不可行。

⑵ 利用rowid结合max或min函数

使用rowid快速唯一确定重复行结合max或min函数来实现删除重复行。
SQL>delete from stu a where rowid not in (select max(b.rowid) from stu b where a.no=b.no and a.name = b.name and a.sex = b.sex); //这里max使用min也可以
或者用下面的语句
SQL>delete from stu a where rowid < (select max(b.rowid) from stu b where a.no=b.no and a.name = b.name and a.sex = b.sex); //这里如果把max换成min的话,前面的where子句中需要把"<"改为">"

跟上面的方法思路基本是一样的,不过使用了group by,减少了显性的比较条件,提高效率。
SQL>delete from stu where rowid not in (select max(rowid) from stu t group by t.no, t.name, t.sex );

思考:若在stu表中唯一确定任意一行数据(1, 'ab',’男’),把sex字段更新为”女”,怎么做?
SQL>update stu set sex=’女’ where rowid=(select min(rowid) from stu where no=1 and name=’ab’ and sex=’男’);


RowID的应用

1,查找和删除重复记录
当试图对库表中的某一列或几列创建唯一索引时,
系统提示 ORA-01452 :不能创建唯一索引,发现重复记录。

/*conn scott/tiger
Create table empa as select * from emp;
插入重复记录
insert into empa select * from emp where empno = 7369;
insert into empa select * from emp where empno = 7839;
insert into empa select * from emp where empno = 7934;
*/
查找重复记录的几种方法:
查找大量重复记录
select empno from empa group by empno having count(*) >1;
Select * From empa Where ROWID Not In(Select Min(ROWID) From empa Group By empno);
查找少量重复记录
select * from empa a where rowid<>(select max(rowid) from empa where empno=a.empno );

删除重复记录的几种方法:
(1).适用于有大量重复记录的情况(列上建有索引的时候,用以下语句效率会很高):
Delete empa Where empno In (Select empno From empa Group By empno Having Count(*) > 1)
And ROWID Not In (Select Min(ROWID) From empa Group By empno Having Count(*) > 1);

Delete empa Where ROWID Not In(Select Min(ROWID) From empa Group By empno);

(2).适用于有少量重复记录的情况(注意,对于有大量重复记录的情况,用以下语句效率会很低):
Delete empa a where rowid<>(select max(rowid) from empa where empno=a.empno );

posted @ 2015-12-03 16:41  孟宇  阅读(1260)  评论(0编辑  收藏  举报