2016-11-07 49 views
0

我有一個表描述如下:的Postgres數據庫建設多外鍵

         Table "public.lead" 
      Column   |    Type    |    Modifiers     
-----------------------------+--------------------------------+----------------------------------------- 
id       | character varying(36)   | not null 
reference_code    | character varying(20)   | not null 
country_id     | character varying(36)   | not null 
language_id     | character varying(36)   | not null 
locale_id     | character varying(36)   | not null 
from_country_id    | character varying(36)   | not null 
to_country_id    | character varying(36)   | not null 
customer_id     | character varying(36)   | not null 
user_id      | character varying(36)   | 
from_date     | date       | not null 
from_date_type    | smallint      | not null default (0)::smallint 
from_street     | character varying(200)   | 
from_postalcode    | character varying(25)   | 
from_city     | character varying(100)   | 
from_country    | character varying(50)   | 
from_apartment_type   | character varying(255)   | not null default '0'::character varying 
from_floor     | smallint      | 
from_rooms     | numeric(3,1)     | 
from_people     | integer      | 
from_squaremeter   | integer      | 
from_elevator    | smallint      | not null 

我試圖創建(COUNTRY_ID,from_country_id,to_country_id)外鍵 正如你可以看到所有這3個領域的有關係與桌子。 但是當我嘗試創建這些外鍵時,出現以下錯誤。

ERROR: insert or update on table "lead" violates foreign key constraint "lead_to_country_id" Detail: Key (to_country_id)=(United Kingdom) is not present in table "country". Details

+0

錯誤是由'insert'或'update'語句引起的。請[編輯]你的問題和所有這些陳述。 –

回答

0

此錯誤通常與缺少的關鍵字有關。

當您嘗試在插入語句後創建外鍵時,SQL將搜索具有主鍵(PK)的表中的那些鍵。

例如,

table_with_PK

col1(Pk) | col2| coln ... 
id_1  foo bar ... 
id_2  nan ana ... 

table_connected_to_table_with_PK

col1(Fk) | col2 | etc... 
id_1 
id_2 
id_3 (Error because not present in table_with_PK) 

所以首先創建具有主鍵的表,然後填充它。

第二次用外鍵創建表,創建外鍵(Fk),然後填充/更新它,以便在數據庫中保持一致。在約束

檢查PostgreSQL文檔:https://www.postgresql.org/docs/current/static/ddl-constraints.html

0

錯誤消息非常說它:您正在嘗試設置to_country_id列值'United Kingdom'不被引用country表中。將該值插入到country表中並重試。