简体   繁体   English

Postgresql 基于其他行的行值约束

[英]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这是否可能,创建这样的约束,允许具有相同valueflag = true的重复行,但最多允许一次具有给定valueflag = 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.我建议不要让flagnot null因为null布尔值很少是你想要的。

See the CREATE INDEX documentation for details.有关详细信息,请参阅CREATE INDEX 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM