首页 > 学院 > 开发设计 > 正文

Oracle索引也可以这么建

2019-11-09 13:34:31
字体:
来源:转载
供稿:网友

 需求是status为new的id需要唯一,其他的数据不做要求。

drop table test purge;

create table test(  id  number,  status varchar2(10));create unique index uind_t_id on test(decode(status,'new',id,null));insert into test values(1,'new'); commit;insert into test values(2,'new'); commit;insert into test values(1,'old'); commit;insert into test values(2,'old'); commit;insert into test values(1,'new'); *第 1 行出现错误:

ORA-00001: 违反唯一约束条件 (UIND_T_ID)

insert into test values(2,'old'); commit;

select * from test;    ID STATUS------- ----------      1 new      2 new      1 old

      2 old

      2 old

可能有同学要问为什么status和id建一个联合的唯一索引,这种做法达不到要求,实验一下:

truncate table test;drop index uind_t_id;         create unique index uind_t_id on test(id,status);insert into test values(1,'new'); commit;insert into test values(2,'new'); commit;insert into test values(1,'old'); commit;insert into test values(2,'old'); commit;insert into test values(1,'new')*第 1 行出现错误:ORA-00001: 违反唯一约束条件 (SPROC4GD_DEV.UIND_T_ID)insert into test values(2,'old')*第 1 行出现错误:ORA-00001: 违反唯一约束条件 (SPROC4GD_DEV.UIND_T_ID)select * from test;        ID STATUS---------- ----------         1 new         2 new         1 old         2 old

可以看到这个不满足其他的数据不做要求的需求。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表