在postgresql中添加一对一的非空约束

前端之家收集整理的这篇文章主要介绍了在postgresql中添加一对一的非空约束前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我在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)
);

我需要做一个约束,以使schoolName或studyingAt不需要为空(其中一个必须有信息).

我该如何做?

您可以使用 check constraint
constraint chk_education check (schoolName is not null or studiedAt is not null)

从手册:

A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression.

编辑:替代遵守无形式解释:

constraint chk_education check ((schoolName is not null and studiedAt is null) or (schoolName is null and studiedAt is not null))

猜你在找的Postgre SQL相关文章