Postgresql约束CHECK条件

时间:2015-11-16 21:22:44

标签: postgresql

我有一个包含列的表:c1,c2,c3,c4 我正在尝试添加CONSTRAINT检查 条件是:

  1. 如果c4不为null,则c1,c2,c3都不能为空。
  2. 如果c4为null,则c1,c2,c3是可选的,但至少有一个字段 必须是非空的。
  3. 这是我的sql命令:

    ADD CONSTRAINT quatereulchk CHECK( 
        (c1 IS NOT NULL AND c2 IS NOT NULL AND c3 IS NOT NULL AND c4 IS NOT NULL) 
        OR 
        (c4 IS NULL AND c1 IS NOT NULL OR c2 IS NOT NULL OR c3 IS NOT NULL)
        );
    

    我用pg_admin测试但是约束不起作用。谢谢!

2 个答案:

答案 0 :(得分:4)

尝试在第二种情况下对“c1 IS NOT NULL或c2 IS NOT NULL或c3 IS NOT NULL”进行分组,例如:

ADD CONSTRAINT quatereulchk CHECK( (c1 IS NOT NULL AND c2 IS NOT NULL AND c3 IS NOT NULL AND c4 IS NOT NULL) OR (c4 IS NULL AND (c1 IS NOT NULL OR c2 IS NOT NULL OR c3 IS NOT NULL)) )

答案 1 :(得分:1)

使用coalesce()

ADD CONSTRAINT quatereulchk CHECK( 
    (c1 IS NOT NULL AND c2 IS NOT NULL AND c3 IS NOT NULL AND c4 IS NOT NULL) 
    OR 
    (c4 IS NULL AND COALESCE(c1, c2, c3) IS NOT NULL)
    );

一些测试:

insert into example values
(null, null, null, null);
ERROR:  new row for relation "example" violates check constraint "quatereulchk"
DETAIL:  Failing row contains (null, null, null, null).

insert into example values
(null, null, 3, null);
INSERT 0 1

insert into example values
(null, 2, 3, 4);
ERROR:  new row for relation "example" violates check constraint "quatereulchk"
DETAIL:  Failing row contains (null, 2, 3, 4).

insert into example values
(1, 2, 3, 4);
INSERT 0 1