2011-10-18 77 views
0
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_dateiddate_dimension
当前的代码无法做到这一点说Postgres的:两个外键,以相同的主键字段

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

谢谢

回答

5

每个FOREIGN KEY约束添加到表将始终在引用表涉及一个一个行*在被引用的。如果您希望引用中的每一行引用重复中的两个不同行,则需要两个单独的外键约束。

你想:

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

你几乎总是希望有确切的外键的行是一样的被引用的主键。

*实际上,如果外键小于参考者的候选键,则参与者可能有多行。这很少有用,但几乎肯定与你描述的问题无关

+0

我现在看到这个 - 错误:关系“date_dimension”的列“id”已经存在 – daydreamer

+0

@daydreamer:这听起来像一个新问题,请到目前为止的所有代码问一个新问题。 – SingleNegationElimination

+0

嗨@TokenMacGuy,这是因为我的愚蠢,你的解决方案是岩石!感谢:) – daydreamer