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_date
和 to_date
都引用到 date_dimension
中的 id
字段?
当前的代码无法做到这一点
ERROR: there is no unique constraint matching given keys for referenced table "date_dimension"
谢谢
最佳答案
添加到表中的每个FOREIGN KEY
约束总是将引用表中的一个 行与引用表中的一个 行*相关联。如果您想让引用中的每一行引用引用中的两个不同的行,您需要两个单独的外键约束。
你想要:
foreign key (from_date) references date_dimension(id)
foreign key (to_date) references date_dimension(id)
您几乎总是希望外键中的行与引用项中的主键完全相同。
* 实际上,如果外键小于引用对象的候选键,则引用对象中可能有不止一行。不过,这很少有用,而且几乎可以肯定与您描述的问题无关
关于database - Postgres : two foreign keys to same primary key field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7815018/