2009-12-03 143 views
25

我使用的是一個oracle表,並且已經在四列創建了一個唯一的約束。約束中的這些列可以有NULL嗎?多列唯一約束

+3

在我看來,這是非常容易的找出答案這與一個測試。這樣做可能需要一分多鐘嗎? – 2009-12-04 09:04:05

+7

是的 - 你說得對。但是我從Vincent,Amber和Shoover發佈的答案中學到了其他信息。 – Nicks 2009-12-04 09:37:04

回答

41

除非列指定爲NOT NULL,否則可以在列中包含NULL。您將能夠但是存儲空值只有一個實例(同一列沒有兩套將被允許,除非所有列是NULL):

SQL> CREATE TABLE t (id1 NUMBER, id2 NUMBER); 

Table created 
SQL> ALTER TABLE t ADD CONSTRAINT u_t UNIQUE (id1, id2); 

Table altered 
SQL> INSERT INTO t VALUES (1, NULL); 

1 row inserted 
SQL> INSERT INTO t VALUES (1, NULL); 

INSERT INTO t VALUES (1, NULL) 

ORA-00001: unique constraint (VNZ.U_T) violated 

SQL> /* you can insert two sets of NULL, NULL however */ 
SQL> INSERT INTO t VALUES (NULL, NULL); 

1 row inserted 
SQL> INSERT INTO t VALUES (NULL, NULL); 

1 row inserted 
2

Oracle中有兩個空值被認爲是不相等的,所以這些列可以包含空值。

5

是的,Oracle允許UNIQUE約束包含具有NULL內容的列,但PRIMARY KEY約束不能包含包含NULL值的列。 (編輯:是「......可爲空的列......」,但下面的示例顯示不是真的.PK中的列可以定義爲可爲空,但不能包含NULL)。

您不能擁有UNIQUE約束和具有相同列的PRIMARY KEY約束。

SQL> create table stest (col1 integer not null, col2 integer null); 

Table created. 

SQL> alter table stest add constraint stest_uq unique (col1, col2); 

Table altered. 

SQL> insert into stest values (1, 3); 

1 row created. 

SQL> insert into stest values (1, null); 

1 row created. 

SQL> insert into stest values (1, null); 
insert into stest values (1, null) 
* 
ERROR at line 1: 
ORA-00001: unique constraint (SUSAN_INT.STEST_UQ) violated 

SQL> insert into stest values (2, null); 

1 row created. 

SQL> commit; 

Commit complete. 

SQL> select * from stest; 

     COL1  COL2 
---------- ---------- 
     1   3 
     1 
     2 

SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2); 
alter table stest add constraint stest_pk PRIMARY KEY (col1, col2) 
                  * 
ERROR at line 1: 
ORA-01449: column contains NULL values; cannot alter to NOT NULL 

SQL> truncate table stest; 

Table truncated. 

SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2); 
alter table stest add constraint stest_pk PRIMARY KEY (col1, col2) 
              * 
ERROR at line 1: 
ORA-02261: such unique or primary key already exists in the table 

SQL> alter table stest drop constraint stest_uq; 

Table altered. 

SQL> alter table stest add constraint stest_pk PRIMARY KEY (col1, col2); 

Table altered.