PostgreSQL-为什么可以';我是否基于unique列创建复合外键,而不将复合键声明为unique?
我注意到,如果引用的键不是唯一的,则无法创建外键,但是,如果我有记录PostgreSQL-为什么可以';我是否基于unique列创建复合外键,而不将复合键声明为unique?,sql,postgresql,foreign-keys,unique-constraint,composite-key,Sql,Postgresql,Foreign Keys,Unique Constraint,Composite Key,我注意到,如果引用的键不是唯一的,则无法创建外键,但是,如果我有记录(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,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)
);
在公开赛中
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)
);
大多数数据库要求外键约束必须是主键或唯一键(两者都可以是复合键) 我不知道有哪些扩展功能允许从主键或唯一键生成列的超集。也许有些数据库确实允许这样做。另一方面,当一个较小的组起作用时,我不容易想到使用额外的辅助键的用途
(注意:我确实能想到一种情况,但Postgres有表继承,这使得使用表继承变得不必要。)+1对于表继承,我不知道这样的功能,这也解决了我的特殊问题。非常感谢。