【发布时间】:2021-05-27 21:56:31
【问题描述】:
我想要一个约束,确保至少有两列不为空。 基本上,从这两列中,一列必须包含值。
我怎么能有这样的约束? 可以在 liquibase 上使用吗?如果没有,是否可以通过 SQL 或某些 postgres 特定的东西?
【问题讨论】:
-
回答dba.SE相关:"Count NULL values per row"
标签: sql postgresql liquibase
我想要一个约束,确保至少有两列不为空。 基本上,从这两列中,一列必须包含值。
我怎么能有这样的约束? 可以在 liquibase 上使用吗?如果没有,是否可以通过 SQL 或某些 postgres 特定的东西?
【问题讨论】:
标签: sql postgresql liquibase
您可以使用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>
【讨论】:
num_nulls()