在postgresql中添加一个二分之一的非空约束

Jim*_*mmy 24 sql postgresql constraints database-schema

如果我在Postgresql中有一个表:

create table Education ( 
    id                  integer references Profiles(id),
    finished            YearValue not null,
    started             YearValue,
    qualification       text,
    schoolName          text,
    studiedAt           integer references Organizations(id),
    primary key (id)
);
Run Code Online (Sandbox Code Playgroud)

我需要创建一个约束,以便schoolName或者studiedAt不需要为null(其中一个必须包含信息).

我该怎么做呢?

Ale*_*aho 38

您可以使用检查约束,例如

constraint chk_education check (schoolName is not null or studiedAt is not null)
Run Code Online (Sandbox Code Playgroud)

从手册:

检查约束是最通用的约束类型.它允许您指定某列中的值必须满足布尔(真值)表达式.

编辑:符合Pithyless解释的替代方案:

constraint chk_education check ((schoolName is not null and studiedAt is null) or (schoolName is null and studiedAt is not null))
Run Code Online (Sandbox Code Playgroud)

  • 这有点晚了,但这是一个XOR约束,所以你可以把它表达为`CHECK((schoolName IS NULL)<>(examineAt IS NULL))` (11认同)
  • 此检查不能防止同时设置 schoolName 和 StudiesAt ,我认为 OP 也考虑到了这一点。 (3认同)
  • 这个问题要求一个变量,该变量至少要在“ schoolName”和“ studiedAt”上强制包含一些信息。尽管我不同意问题的解释,但我添加了一个符合您评论的约束变体。 (2认同)
  • 如果表已经存在,您可以使用:`ALTER TABLE Education ADD CONSTRAINT chk_schoolName_studiedAt CHECK ((schoolName IS NULL) &lt;&gt; (studiedAt IS NULL))` (2认同)