2011-10-18 80 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