我有一张如下表:
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 9.2.3 我试图创建这个简化的表:
CREATE TABLE test (
user_id INTEGER,
startend TSTZRANGE,
EXCLUDE USING gist (user_id WITH =, startend WITH &&)
);
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
Run Code Online (Sandbox Code Playgroud)ERROR: data type integer has no default operator class for access method "gist" HINT: You must specify an operator class for the index or define a default operator class for the data type.
在PostgreSQL的文档使用这个例子不为我工作:
CREATE TABLE room_reservation (
room text,
during tsrange,
EXCLUDE USING gist (room WITH =, during WITH &&)
);
Run Code Online (Sandbox Code Playgroud)
同样的错误信息。
而这个对我来说也不起作用: …
postgresql constraint installation exclusion-constraint gist-index