我使用的是一个oracle表,并且已经在四列创建了一个唯一的约束。约束中的这些列可以有NULL吗?多列唯一约束
Q
多列唯一约束
25
A
回答
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.
相关问题
- 1. 多列唯一约束
- 2. DB2 - 唯一约束多列
- 3. SQLite表约束 - 在多列上唯一
- 4. 指数多列的唯一约束
- 5. 唯一约束外键列
- 6. 添加唯一约束列
- 7. 唯一约束
- 8. 唯一约束(SchemaName.DATA1_PK)
- 9. 唯一约束值
- 10. 唯一约束JayData
- 11. 唯一约束Nhibernate
- 12. SQL跨多个表的唯一约束
- 13. sqlite列约束唯一和外部
- 14. 表列上的唯一约束条件
- 15. 可空列的唯一约束
- 16. 查找列是否有唯一约束
- 17. 2列组合的SQL唯一约束
- 18. 删除H2中列的唯一约束
- 19. 超过10列的唯一约束
- 20. 唯一约束vs唯一索引
- 21. Oracle唯一约束和唯一索引
- 22. 多列约束
- 23. PK和唯一约束
- 24. 复合唯一约束SQL
- 25. 笨ORA-00001:唯一约束
- 26. 冬眠唯一约束
- 27. 在唯一键约束
- 28. DataTable上的唯一约束
- 29. HABTM - 唯一性约束
- 30. 唯一约束异常(SQLIntegrityConstraintViolationException)
在我看来,这是非常容易的找出答案这与一个测试。这样做可能需要一分多钟吗? – 2009-12-04 09:04:05
是的 - 你说得对。但是我从Vincent,Amber和Shoover发布的答案中学到了其他信息。 – Nicks 2009-12-04 09:37:04