关于唯一键(Unique)

SQL> create table test_ranbo(id number);
 
Table created
 
SQL> alter table test_ranbo add constraint test_ranbo$uk unique (id);
 
Table altered

SQL> insert into test_ranbo(id) values(null);
 
1 row inserted
 
SQL> insert into test_ranbo(id) values(null);
 
1 row inserted

可以插入两个null.

下面建个包含两列外键的例子。

SQL> truncate table test_Ranbo;
 
Table truncated
 
SQL> alter table test_ranbo drop constraint test_ranbo$uk;
 
Table altered
 
SQL> alter table test_ranbo add Name varchar2(30);
 
Table altered
 
SQL> desc test_ranbo;
Name Type         Nullable Default Comments
---- ------------ -------- ------- --------
ID   NUMBER       Y                        
NAME VARCHAR2(30) Y                        
 
SQL> alter table test_ranbo add constraint test_ranbo$uk unique (id ,name);
 
Table altered
 
SQL> insert into test_ranbo values(1,null);
 
1 row inserted
 
SQL> insert into test_ranbo  values(1,null);
 
insert into test_ranbo  values(1,null)
 
ORA-00001: unique constraint (DBOWN.TEST_RANBO$UK) violated

再由测试外键是三列的情况。

SQL> truncate table test_ranbo;
 
Table truncated
 
SQL> alter table test_ranbo drop constraint test_ranbo$uk;
 
Table altered
 
SQL> alter table test_ranbo add type varchar2(30);
 
Table altered
 
SQL> desc test_ranbo;
Name Type         Nullable Default Comments
---- ------------ -------- ------- --------
ID   NUMBER       Y                        
NAME VARCHAR2(30) Y                        
TYPE VARCHAR2(30) Y                        
 
SQL> alter table test_ranbo add constraint test_ranbo$uk unique (id,name,type);
 
Table altered
 
SQL> insert into test_ranbo(id,name,type) values(1,null,null);
 
1 row inserted
 
SQL> /
 
insert into test_ranbo(id,name,type) values(1,null,null)
 
ORA-00001: unique constraint (DBOWN.TEST_RANBO$UK) violated

SQL> insert into test_ranbo(id,name,type) values(null,null,null);
 
1 row inserted
 
SQL> /
 
1 row inserted

SQL> insert into test_ranbo(id,name,type) values(null,'a',null);
 
1 row inserted
 
SQL> /
 
insert into test_ranbo(id,name,type) values(null,'a',null)
 
ORA-00001: unique constraint (DBOWN.TEST_RANBO$UK) violated

由此可见,在唯一键包含两列以上的情况下,只要有了一列是非null,那么其他列的null可以理解为一个确定的值,唯一键会起作用,只有唯一键的所有列都是null值的时候不管插入多少行相同的记录唯一键都不起作用。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/13387766/viewspace-608824/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/13387766/viewspace-608824/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值