【问题标题】:Composite Not Null constraint on two columns两列上的复合非空约束
【发布时间】:2021-05-27 21:56:31
【问题描述】:

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

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

【问题讨论】:

标签: sql postgresql liquibase


【解决方案1】:

您可以使用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 )
       

【讨论】:

  • 我会试试这个!但这似乎很有希望,并没有出现在我的脑海中。你就是男人。
  • 这个一般逻辑有效,我赞成你的回答,但会将另一个标记为已批准,因为他还提到了如何使用 liquibase 来做到这一点
【解决方案2】:

我喜欢为此使用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>

【讨论】:

  • 这是一个我不知道的奇怪功能。这在 Postgres 中很容易编码,我想知道它为什么会存在。但无论如何,我学到了一些东西。
  • @GordonLinoff:是的,它真的很方便。 “对面”也有num_nulls()
  • 感谢您展示这个 :) 我也没有听说过 :)
猜你喜欢
  • 2022-01-14
  • 2018-03-18
  • 2021-11-02
  • 1970-01-01
  • 2018-11-17
  • 1970-01-01
  • 2018-05-28
  • 2019-08-15
  • 2016-02-14
相关资源
最近更新 更多