gpt4 book ai didi

sql - 在 postgresql 中添加二选一非空约束

转载 作者:行者123 更新时间:2023-11-29 11:08:35 25 4
gpt4 key购买 nike

如果我在 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)
);

我需要进行约束,以便 schoolNamestudiedAt 不能为 null(其中之一必须包含信息)。

我该怎么做?

最佳答案

您可以使用 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.

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

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

关于sql - 在 postgresql 中添加二选一非空约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5447880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com