如何在 PostgreSQL 中使用多列添加 CHECK 约束

How to add CHECK constraints using multiple columns in PostgreSQL

我在 Postgresql 中对这种不相交建模时遇到了问题。错误信息显示:

错误:“或”处或附近的语法错误 第 2 行:添加约束 group_collection 或 user_collection Check (g ... ^ 我该怎么做才能解决这个问题?

create table collections(
collectionId    serial,
title           TitleValue,
description     text,
key             integer not null,
group_coll_id   integer,
user_coll_id    integer,
primary key (collectionId),
foreign key (key) references photos(photoid)

----照片来自以前table--- );

create table group_collection(
group_coll_id   integer,
owns            integer not null,
primary key (group_coll_id),
foreign key (group_coll_id) references collections(collectionId),
foreign key (owns) references groups(groupid)

);

create table user_collection(
user_coll_id    integer,
owns            integer not null,
primary key (user_coll_id),
foreign key (user_coll_id) references collections(collectionId),
foreign key (owns) references users(userid)

);

alter table collections add constraint  fk_collections_group foreign key (group_coll_id) references group_collection(group_coll_id);
alter table collections add constraint  fk_collections_user foreign key (user_coll_id) references user_collection(user_coll_id);
alter table only collections
add constraint group_collection or user_collection Check (group_coll_id is null or user_coll_id is null)

欢迎来到 SO。您将约束命名为 group_collection or user_collection,这不是有效标签 :)

table CREATE TABLE t (x INT, y INT);ADD CONSTRAINT 语法应该是

    ALTER TABLE t ADD CONSTRAINT any_label CHECK (x IS NULL OR y IS NULL)

这应该适用于您的情况:

alter table collections
add constraint mycheck check (group_coll_id is null or user_coll_id is null)

演示:db<>fiddle