【问题标题】:Postgres: two foreign keys to same primary key fieldPostgres:同一个主键字段的两个外键
【发布时间】:2011-10-18 23:37:47
【问题描述】:
create table date_dimension (
id serial primary key,
date_id date,
..... others
);

create table temp (
id serial primary key,
from_date integer,
to_date integer,
value integer,
foreign key (from_date, to_date) references date_dimension(id, id)
);  

如何将from_dateto_date 都引用到date_dimension 中的id 字段?
当前代码无法做到这一点

ERROR:  there is no unique constraint matching given keys for referenced table "date_dimension"  

谢谢

【问题讨论】:

    标签: database postgresql foreign-keys


    【解决方案1】:

    每个添加到表的FOREIGN KEY 约束将始终将引用表中的 one 行与引用表中的 one 行* 相关联。如果您想让引用中的每一行引用引用中的两个不同行,则需要两个单独的外键约束。

    你想要的:

    foreign key (from_date) references date_dimension(id)
    foreign key (to_date) references date_dimension(id)
    

    您几乎总是希望外键中的行与引用中的主键完全相同。

    * 实际上,如果外键小于引用对象的候选键,则引用对象中可能不止一行。但是,这很少有用,而且几乎可以肯定与您描述的问题无关

    【讨论】:

    • 我现在看到了 - 错误:关系“date_dimension”的列“id”已经存在
    • @daydreamer:这听起来像是一个新问题,请用你目前拥有的所有代码提出一个新问题。
    • 嗨@TokenMacGuy,这是由于我的愚蠢,你的解决方案太棒了!谢谢你:)
    • 你需要在这里添加索引吗?
    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2011-03-20
    • 2017-01-16
    相关资源
    最近更新 更多