【问题标题】:PostgreSQL - Why can't I create composite foreign key based on unique column without declaring composite key as unique?PostgreSQL - 为什么我不能在不将复合键声明为唯一的情况下基于唯一列创建复合外键?
【发布时间】: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


    【解决方案1】:

    大多数数据库要求外键约束是主键或唯一键(两者都可以是复合键)。

    我不知道允许来自主键或唯一键的列超集的扩展功能。也许某些数据库确实允许这样做。另一方面,当较小的集合起作用时,我不能轻易想到使用额外的辅助键的用途。

    (警告:我实际上可以想到一种情况,但 Postgres 具有表继承,因此无需使用。)

    【讨论】:

    • +1 用于提及表继承,我不知道这样的功能,这也解决了我的特殊问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    相关资源
    最近更新 更多