【问题标题】:NOT NULL constraint on a column when another column has a particular value当另一列具有特定值时,列上的 NOT NULL 约束
【发布时间】:2014-05-25 06:02:11
【问题描述】:
create table test (
    col1 varchar(20),
    col2 varchar(20)
)
  1. 当 col1 的值为“1”时,col2 不能为空。
  2. 当 col1 有任何其他值时,col2 可以为 null。

有没有办法根据特定列的值编写检查约束?

【问题讨论】:

    标签: postgresql check-constraints


    【解决方案1】:

    你可以写一个表级的约束,当然。

    CREATE TABLE test (
        col1 VARCHAR(20),
        col2 VARCHAR(20),
        CHECK (col1 != '1' OR col2 IS NOT NULL)
    );
    

    要么col1 不是'1'(col2 可以是任何东西),要么col1'1'(并且col2 不能为空)。

    请参阅third example in the manual

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 2021-10-07
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多