我有一张描述如下的表:
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个字段都与表有关系。 但是当我尝试创建这些外键时,我收到了以下错误。
错误:在表格上插入或更新"引导"违反外键约束" lead_to_country_id"详细信息:表(" country")中不存在键(to_country_id)=(英国)。 细节
答案 0 :(得分: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
答案 1 :(得分:0)
错误消息几乎说明了:您正在尝试将to_country_id
列值设置为'United Kingdom'
,这在引用的country
表中不存在。将该值插入country
表并重试。