多列唯一约束

42

我正在使用Oracle表,并在四个列上创建了一个唯一约束。这些列在约束中可以为NULL吗?


4
用测试来找到这个答案似乎非常简单,不可能花费超过一分钟的时间,这是我的看法。 - David Aldridge
11
没错,你说得对。但我从Vincent、Amber和Shoover发布的答案中学到了其他信息。 - Nicks
你是对的!哇,你也是对的! - er-han
3个回答

71

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

如果您的表有3列,而您只想要前两列唯一,我不确定如何使用这种方法实现。 - Collin

5
是的,Oracle允许UNIQUE约束包含具有NULL内容的列,但是PRIMARY KEY约束不能包含包含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.

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

我的情况并不属实(Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production)。我在两个列上使用多个约束(可空VARCHAR2和NUMBER),我无法插入两行具有相同数字和空值的数据。 - honzakuzel1989
我认为在这种情况下最好用一个例子来回答,因为这样可以澄清问题并显示你的陈述是有效的,而其他答案(包括被接受的答案)也是如此。在这种情况下,我认为这个陈述是不正确的,而被接受的答案也清楚地说明了为什么它是不正确的。 - Peter Merkert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接