两列上的复合非空约束

Composite Not Null constraint on two columns

我想要一个约束,其中我确保至少有两列不为空。 基本上,从这两列中,一列必须包含值。

我怎么会有这样的约束? 在 liquibase 上有可能吗?如果没有,是否可以通过 SQL 或一些 postgres 特定的东西?

您可以使用 check 约束。对于至少一个非 NULL 值:

check (col1 is not null or col2 is not null)

如果您只需要一个来包含值:

check (col1 is not null and col2 is null or
       col1 is null and col2 is not null
      )

或者在 Postgres 中:

check ( (col1 is not null)::int + (col2 is not null)::int = 1 )
       

我喜欢为此使用 num_nonnulls():

对于至少一个非空列:

check (num_nonnulls(col1, col2) >= 1)

恰好有一个非空列:

check (num_nonnulls(col1, col2) = 1)

Liquibase 没有针对检查约束的内置更改(至少在社区版本中没有),因此您需要为此进行 <sql> 更改:

<sql> 
  alter table the_table
    add constraint at_least_one_not_null
    check (num_nonnulls(col1, col2) >= 1)   
</sql>