postgres添加约束以确保如果另一列不为空则一列不为空

d_a*_*a_n 4 postgresql constraints

Postgres 9.3

我有两个整数类型列“a”和“b”。有效选项有:

  • “a”为空,“b”为空
  • “a”不为空,“b”为空
  • “a”不为空,“b”不为空

我正在尝试添加一个检查/约束来防止无效选项:

  • “a”为空,“b”不为空

我将不胜感激任何帮助。

预先感谢丹

Clo*_*eto 5

create table t (
    a int,
    b int,
    check (
        a is null and b is null
        or
        a is not null and b is null
        or
        a is not null and b is not null
    )
);

insert into t (a, b) values
(null, null),
(1, null),
(1, 1),
(null, 1);
ERROR:  new row for relation "t" violates check constraint "t_check"
DETAIL:  Failing row contains (null, 1).
Run Code Online (Sandbox Code Playgroud)