我注意到,如果引用的键不是唯一的,则无法创建外键,但是,如果我有记录 (x, y, z)
其中 x
是唯一的,假设每条记录将始终是唯一的是“直观的”。
那么,有没有什么特别的原因我没有考虑为什么我不能做这样的事情
create table x(
id int primary key,
something int not null
);
create table y(
id serial primary key, -- whatever, this doesn't matter
x_id int not null,
x_something int not null,
foreign key (x_id, x_something)
references x(id, something)
);
在 Postgres 中抛出
ERROR: there is no unique constraint matching given keys for referenced table "x"
并且可以通过在表 x
中添加 unique (id, something)
来更正。
这种行为是只存在于 Postgres 中,还是在 SQL 标准中有定义?
有没有什么方法可以在不需要 unique
约束的情况下引用复合键?
编辑 1: 这是一个有用的情况示例
create table movie_reservation(
id serial primary key,
movie_id int references(...),
-- ... (reservation data like the time and interval),
seen boolean not null default false -- wether a user has seen it
);
-- want califications of moves that HAVE BEEN SEEN
create table movie_calification(
movie_reservation_id int not null,
seen boolean
not null
check (boolean = true),
stars smallint
not null
check (stars between 1 and 5),
foreign key (movie_reservation_id, seen)
references movie_reservation(id, seen)
);
最佳答案
大多数数据库要求外键约束是主键或唯一键(两者都可以是复合键)。
我不知道允许来自主键或唯一键的列超集的扩展功能。也许某些数据库确实允许这样做。另一方面,当较小的集合起作用时,我无法轻易想到使用额外的辅助 key 的用途。
(警告:我实际上可以想到一种情况,但 Postgres 具有表继承,因此没有必要使用这种情况。)
关于sql - PostgreSQL - 为什么我不能在不将复合键声明为唯一的情况下基于唯一列创建复合外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42588304/