【发布时间】:2017-03-03 20:56:26
【问题描述】:
我注意到,如果引用的键不是唯一的,则您无法创建外键,但是,如果我有记录 (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)
);
【问题讨论】:
标签: sql postgresql foreign-keys unique-constraint composite-key