Primary key 與Unique Key都是唯一性約束。但二者有很大的區(qū)別: 1、Primary key的1個或多個列必須為NOT NULL,如果列為NULL,在增加PRIMARY KEY時,列自動更改為NOT NULL。而UNIQUE KEY 對列沒有此要求。 2、一個表只能有一個PRIMARY KEY,但可以有多個UNIQUE KEY。 下面以測試說明: 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兩個列都自動改為了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。 注意到,在刪除主鍵時,列的NULLABLE會回到原來的狀態(tài)。如果在創(chuàng)建主鍵后,對原來為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) 再做如下的實驗: 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. 可以看到可以增加兩個UNIQUE KEY??纯茨懿荒茉黾觾蓚€主鍵: 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> / 主鍵和唯一鍵約束是通過參考索引實施的,如果插入的值均為NULL,則根據(jù)索引的原理,全NULL值不被記錄在索引上,所以插入全NULL值時,可以有重復(fù)的,而其他的則不能插入重復(fù)值。 |
|