She*_*oss 8 postgresql constraints unique-key
我想要一个解决方案,只有当列不为null时才强制执行约束.我似乎无法在文档中找到这样做的方法.
create table mytable(
table_identifier_a INTEGER,
table_identifier_b INTEGER,
table_value1,...)
Run Code Online (Sandbox Code Playgroud)
根据数据的性质,我将在创建表时使用标识符b和值.在我们收到其他数据后,我将能够填充标识符a.此时我想确保一个unique key of (identifier_a, value1)但仅限于identifier_a存在.
希望这是有道理的,任何人都有任何想法?
嗯.唯一约束不会阻止多个NULL值.
CREATE TABLE mytable (
table_identifier_a INTEGER NULL,
table_identifier_b INTEGER NOT NULL,
table_value1 INTEGER NOT NULL,
UNIQUE(table_identifier_a, table_identifier_b)
);
Run Code Online (Sandbox Code Playgroud)
请注意,即使identifier_b匹配,我们也可以在其中插入多个NULL:
test=# INSERT INTO mytable values(NULL, 1, 2);
INSERT 0 1
test=# INSERT INTO mytable values(NULL, 1, 2);
INSERT 0 1
test=# select * from mytable;
table_identifier_a | table_identifier_b | table_value1
--------------------+--------------------+--------------
| 1 | 2
| 1 | 2
(2 rows)
Run Code Online (Sandbox Code Playgroud)
但是我们不能创建重复的(a,b)对:
test=# update mytable set table_identifier_a = 3;
ERROR: duplicate key value violates unique constraint "mytable_table_identifier_a_key"
Run Code Online (Sandbox Code Playgroud)
当然,您确实遇到了问题:您的表没有主键.您可能有数据模型问题.但是你没有提供足够的细节来解决这个问题.
| 归档时间: |
|
| 查看次数: |
2134 次 |
| 最近记录: |