2009-12-03 5 views
25

Oracle 테이블을 사용하고 있고 4 개의 열에 대해 고유 제한 조건을 만들었습니다. 제약 조건 내의 이들 열에 NULL이 포함될 수 있습니까?다중 열에 대한 고유 제한 조건

+3

그것은 나에게 보인다는에 대한 답을 찾기 위해 아주 사소한 것을 테스트와 함께. 그렇게하는 데 1 분 이상 걸릴 수 있습니까? –

+7

예 - 당신 말이 맞습니다. 그러나 Vincent, Amber 및 Shoover가 게시 한 답변에서 다른 정보를 배웠습니다. – Nicks

답변

41

열이 NOT NULL로 지정되어 있지 않으면 열에 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

두 개의 null은 Oracle에서 같지 않은 것으로 간주되므로이 열에는 null이 포함될 수 있습니다.

5

예, Oracle은 UNIQUE 제약 조건에 NULL 내용이 포함 된 열을 포함 할 수 있지만 PRIMARY KEY 제약 조건에는 NULL 값을 포함하는 열을 포함 할 수 없습니다. (편집 : "nullable columns ..."였지만, 아래의 예는 사실이 아님을 나타냅니다. PK의 열은 null 허용으로 정의 될 수 있지만 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. 
관련 문제