|
Primary key 與Unique Key都是唯一性約束。但二者有很大的區(qū)別: 1、Primary key的1個(gè)或多個(gè)列必須為NOT NULL,如果列為NULL,在增加PRIMARY KEY時(shí),列自動(dòng)更改為NOT NULL。而UNIQUE KEY 對(duì)列沒(méi)有此要求。 2、一個(gè)表只能有一個(gè)PRIMARY KEY,但可以有多個(gè)UNIQUE KEY。 下面以測(cè)試說(shuō)明: SQL> create table t (a int,b int,c int,d int); Table created. SQL> desc t A NUMBER(38) SQL> alter table t add constraint pk_t primary key (a,b); Table altered. SQL> desc t A NOT NULL NUMBER(38) 可以看到A、B兩個(gè)列都自動(dòng)改為了NOT NULL SQL> alter table t modify (a int null); SQL> alter table t drop constraint pk_t; Table altered. SQL> alter table t add constraint uk_t_1 unique (a,b); Table altered. SQL> desc t A NUMBER(38) 我們看到列A又變回了NULL。 注意到,在刪除主鍵時(shí),列的NULLABLE會(huì)回到原來(lái)的狀態(tài)。如果在創(chuàng)建主鍵后,對(duì)原來(lái)為NULL的主鍵列,顯式設(shè)為NOT NULL,在刪除主鍵后仍然是NOT NULL。比如在創(chuàng)建主鍵后,執(zhí)行下面的操作,可以看到: SQL> alter table t modify (b int not null); Table altered. SQL> alter table t drop constraint pk_t; Table altered. SQL> desc t A NUMBER(38) 再做如下的實(shí)驗(yàn): SQL> drop table t; Table dropped. SQL> create table t (a int,b int,c int,d int); Table created. SQL> alter table t add constraint uk_t_1 unique (a,b); Table altered. SQL> alter table t add constraint uk_t_2 unique (c,d); Table altered. 可以看到可以增加兩個(gè)UNIQUE KEY。看看能不能增加兩個(gè)主鍵: SQL> alter table t add constraint pk_t primary key (c); Table altered. SQL> alter table t add constraint pk1_t primary key (d); SQL> alter table t drop constraint pk_t; Table altered. SQL> insert into t (a ,b ) values (null,null); 1 row created. SQL> / 1 row created. SQL> insert into t (a ,b ) values (null,1); 1 row created. SQL> /
1 row created. SQL> / 主鍵和唯一鍵約束是通過(guò)參考索引實(shí)施的,如果插入的值均為NULL,則根據(jù)索引的原理,全NULL值不被記錄在索引上,所以插入全NULL值時(shí),可以有重復(fù)的,而其他的則不能插入重復(fù)值。 |
|
|
來(lái)自: yongcheng.min > 《數(shù)據(jù)庫(kù)》