相关疑难解决方法(0)

PostgreSQL 多列唯一约束和 NULL 值

我有一张如下表:

create table my_table (
    id   int8 not null,
    id_A int8 not null,
    id_B int8 not null,
    id_C int8 null,
    constraint pk_my_table primary key (id),
    constraint u_constrainte unique (id_A, id_B, id_C)
);
Run Code Online (Sandbox Code Playgroud)

我想(id_A, id_B, id_C)在任何情况下都与众不同。所以下面的两个插入肯定会导致错误:

INSERT INTO my_table VALUES (1, 1, 2, NULL);
INSERT INTO my_table VALUES (2, 1, 2, NULL);
Run Code Online (Sandbox Code Playgroud)

但它没有按预期运行,因为根据文档,两个NULL值不会相互比较,因此两个插入都没有错误地通过。

我怎么能保证我的唯一约束,即使id_C可以NULL在这种情况下?实际上,真正的问题是:我可以在“纯 sql”中保证这种唯一性,还是必须在更高级别(在我的情况下为 java)来实现它?

postgresql null constraint unique-constraint

137
推荐指数
3
解决办法
13万
查看次数

标签 统计

constraint ×1

null ×1

postgresql ×1

unique-constraint ×1