如果另一列中的值为 true,则 NOT NULL

geo*_*row 10 postgresql constraint

我有一张与这张相似的桌子

create table my_table
(
id serial,
attribute boolean,
number integer
)
Run Code Online (Sandbox Code Playgroud)

有没有办法让它在列numberIF attributevalue is 中强制不为空true

因此,如果使用属性值“true”保存记录,则必须为 number 指定一个值。

编辑:经过一些挖掘,我试过这个

alter table my_table 
add constraint number_must_have_value CHECK (attribute = 't' and number IS NOT NULL)
Run Code Online (Sandbox Code Playgroud)

它抛出约束被某行违反,但如果我运行:

select * from my_table where attribute = 't' and number IS NOT NULL 
Run Code Online (Sandbox Code Playgroud)

我检索 0 行。所以我的数据似乎没问题?

无论如何,我尝试使用

constraint number_must_have_value NOT VALID CHECK (attribute = 't' and number IS NOT NULL)
Run Code Online (Sandbox Code Playgroud)

但无法使 NOT VALID 选项起作用。我收到语法错误。是不是在正确的地方?

ype*_*eᵀᴹ 23

这是一个相当简单的CHECK约束:

CREATE TABLE my_table
(
id serial,
attribute boolean,
number integer,
CONSTRAINT if_attribute_then_number_is_not_null 
   CHECK ( (NOT attribute) OR (number IS NOT NULL) ) 
) ;
Run Code Online (Sandbox Code Playgroud)

代码背后的逻辑if a then b是逻辑限制用布尔逻辑写成(not a) or (b). 乍一看似乎违反直觉,但如果您编写可能的布尔组合,它就会解决。

约束也可以写成CHECK ( NOT (attribute AND number IS NULL) )这似乎更具解释性(“不允许属性为假且数字同时为空”)。选择对您来说更易读的内容。