如果我在 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
或 studiedAt
不能为空(其中一个必须包含信息)。
我该怎么做?
您可以使用检查约束,例如
constraint chk_education check (schoolName is not null or studiedAt is not null)
来自手册:
检查约束是最通用的约束类型。它允许您指定某一列中的值必须满足布尔(真值)表达式。
编辑:遵守 Pithyless 解释的替代方案:
constraint chk_education check ((schoolName is not null and studiedAt is null) or (schoolName is null and studiedAt is not null))
您还可以在更新和插入时使用触发器来检查在允许数据进入表之前是否遵循规则。当检查约束需要更复杂的逻辑时,您通常会使用这种类型的方法。
这是我在“向上”功能中对续集迁移文件的解决方案
queryInterface.addConstraint('Education', {
fields: ['schoolName', 'studiedAt'],
type: 'check',
name: 'schoolName_or_studiedAt_is_null',
where: { [Sequelize.Op.or]: [{ password: null }, { googleId: null }] },
}),
参加聚会超级晚,但这也有效:
constraint validate_null check (not(schoolName is null and studiedAt is null))