转载自:http://www.csdn.net/article/1970-01-01/278287
平时工作中可能会遇到当试图对库表中的某一列或几列创建唯一索引时,系统提示 ORA-01452 :不能创建唯一索引,发现重复记录。
表CZ的结构如下:
sql> desc cz
Name Null? Type
-------------------------------------------------------------------
C1 NUMBER(10)
C10 NUMBER(5)
C20 VARCHAR2(3)
(1).在Oracle中,每一条记录都有一个rowid,rowid在整个数据库中是唯一的,rowid确定了每条记录是在Oracle中的哪一个数据文件、块、行上。
(2).在重复的记录中,可能所有列的内容都相同,但rowid不会相同,所以只要确定出重复记录中那些具有最大rowid的就可以了,其余全部删除。
重复记录判断的标准是:
C1,C10和C20这三列的值都相同才算是重复记录。
经查看表CZ总共有16条记录:
sql>set pagesize 100
sql>select * from cz;
C1 C10 C20
---------- ---------- ---
1 2 dsf
1 2 dsf
1 2 dsf
1 2 dsf
2 3 che
1 2 dsf
1 2 dsf
1 2 dsf
1 2 dsf
2 3 che
2 3 che
2 3 che
2 3 che
3 4 dff
3 4 dff
3 4 dff
4 5 err
5 3 dar
6 1 wee
7 2 zxc
20 rows selected.
1.查找重复记录的几种方法:
(1).sql>select * from cz group by c1,c10,c20 having count(*) >1;
C1 C10 C20
----------------------- 1 2 dsf
2 3 che
3 4 dff
(2).sql>select distinct * from cz;
C1 C10 C20
----------------------- 1 2 dsf
2 3 che
3 4 dff
(3).sql>select * from cz a where rowid=(select max(rowid) from cz where c1=a.c1 and c10=a.c10 and c20=a.c20);
C1 C10 C20
----------------------- 1 2 dsf
2 3 che
3 4 dff
(1).适用于有大量重复记录的情况(在C1,C10和C20列上建有索引的时候,用以下语句效率会很高):
sql>delete from cz where (c1,c20) in (select c1,c20 from cz group by c1,c20 having count(*)>1) and rowid not in (select min(rowid) from cz group by c1,c20 having count(*)>1);
sql>delete from cz where rowid not in(select min(rowid) from cz group by c1,c20);
(2).适用于有少量重复记录的情况(注意,对于有大量重复记录的情况,用以下语句效率会很低):
sql>delete from cz a where a.rowid!=(select max(rowid) from cz b where a.c1=b.c1 and a.c10=b.c10 and a.c20=b.c20);
sql>delete from cz a where a.rowid<(select max(rowid) from cz b where a.c1=b.c1 and a.c10=b.c10 and a.c20=b.c20);
sql>delete from cz a where a.rowid <(select max(rowid) from cz where c1=a.c1 and c10=a.c10 and c20=a.c20);
(3).适用于有少量重复记录的情况(临时表法):
sql>create table test as select distinct * from cz; (建一个临时表test用来存放重复的记录)
sql>truncate table cz; (清空cz表的数据,但保留cz表的结构)
sql>insert into cz select * from test; (再将临时表test里的内容反插回来)
原文链接:https://www.f2er.com/oracle/207298.html