多列的唯一约束

时间:2009-12-03 17:07:24

标签: oracle unique-constraint

我正在使用oracle表并在四列上创建了一个唯一约束。约束中的这些列是否可以为NULL?

3 个答案:

答案 0 :(得分:55)

除非指定的列为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

答案 1 :(得分: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.

答案 2 :(得分:3)

Oracle中认为两个空值不相等,因此这些列中可以包含空值。