[英]Postgresql Constraint on row value based on other rows
Given the following schema给定以下架构
CREATE TABLE test (
value text,
flag bool
);
is this possible, to create such constraint which would allow duplicate rows with the same value
and flag = true
, but would allow at most once row with the given value
and flag = false
这是否可能,创建这样的约束,允许具有相同value
和flag = true
的重复行,但最多允许一次具有给定value
和flag = false
的行
eg例如
These should execute without errors这些应该执行没有错误
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', true);
INSERT INTO test (value, flag) VALUES ('1', false);
INSERT INTO test (value, flag) VALUES ('1', false);
INSERT INTO test (value, flag) VALUES ('1', true);
And this should raise an error这应该会引发错误
INSERT INTO test (value, flag) VALUES ('1', false);
INSERT INTO test (value, flag) VALUES ('1', false);
I have tried playing with EXCLUDE
constraint but was unable to make it work.我曾尝试使用EXCLUDE
约束,但无法使其工作。
You're looking for a unique partial index:您正在寻找一个唯一的部分索引:
create unique index no_false_duplicates on test (value, flag) where not flag
You'll have to figure out what you want to do about null
values in flag
of course.当然,您必须弄清楚您想对flag
中的null
值做什么。 I'd recommend making the flag
column not null
since null
booleans are rarely what you want.我建议不要让flag
列not null
因为null
布尔值很少是你想要的。
See the CREATE INDEX documentation for details.有关详细信息,请参阅CREATE INDEX 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.