TIP如何为表加唯一约束(保存或者删除冗余的数据)

王朝other·作者佚名  2008-05-19
宽屏版  字体: |||超大  

前几天还被人问起有没有什么方法,在已有冗余的表上加唯一约束; 当然要删除冗余的数据了;我告诉他

SELECT * FROM emp a

WHERE rowid ANY

(SELECT rowid FROM emp b

WHERE a.ename = b.ename

)

可以找到冗余的数据

今个发现还有一个比较简便的方法,如下使用 exceptions into exceptions;

SQL create table t ( a int, b int, c int );

表已创建。

SQL insert into t select rownum,rownum+1,rownum+2 from all_objects where rownum

<5;

已创建4行。

SQL insert into t select *from t where rownum<3;

已创建2行。

SQL commit;

提交完成。

SQL select *from t;

A

B

C

---------- ---------- ----------

1

2

3

2

3

4

3

4

5

4

5

6

1

2

3

2

3

4

已选择6行。

SQL create table exceptions(row_id rowid,

2

owner varchar2(30),

3

table_name varchar2(30),

4

constraint varchar2(30));

表已创建。

SQL

SQL alter table t add constraint t_unique

2

unique(a,b,c) exceptions into exceptions;

alter table t add constraint t_unique

*

ERROR 位于第 1 行:

ORA-02299: 无法验证 (EPUSER.T_UNIQUE) - 未找到重复关键字

SQL create table dups

2

as select *from t where rowid in (select row_id from exceptions);

表已创建。

SQL select *from dups;

A

B

C

---------- ---------- ----------

1

2

3

2

3

4

1

2

3

2

3

4

SQL select row_id from exceptions;

ROW_ID

------------------

AAAIEJAAKAAAyMSAAA

AAAIEJAAKAAAyMSAAE

AAAIEJAAKAAAyMSAAB

AAAIEJAAKAAAyMSAAF

SQL delete from t where rowid in ( select row_id

2

from exceptions );

已删除4行。

SQL insert into t select distinct * from dups;

已创建2行。

SQL

SQL commit;

提交完成。

SQL select *from t;

A

B

C

---------- ---------- ----------

3

4

5

4

5

6

1

2

3

2

3

4

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有