table 约束中不存在 postgres 密钥

postgres key is not present in table constraint

当尝试在 Postgres 9.5 中更改 TABLE 以创建外键约束时:从 product_template.product_brand_idproduct_brand.id

ALTER TABLE public.product_template
    ADD CONSTRAINT product_template_product_brand_id_fkey 
    FOREIGN KEY (product_brand_id)
    REFERENCES public.product_brand (id) MATCH SIMPLE
    ON UPDATE NO ACTION
    ON DELETE SET NULL;

Returns错误

ERROR:  insert or update on table "product_template" violates foreign key         constraint "product_template_product_brand_id_fkey"
DETAIL:  Key (product_brand_id)=(12) is not present in table "product_brand".
STATEMENT:  ALTER TABLE "product_template" ADD FOREIGN KEY ("product_brand_id") REFERENCES "product_brand" ON DELETE set null

当 fkey 从 product_template.product_brand_idproduct_brand.id

时,我很困惑为什么 postgres 试图找到 product_brand.product_brand_id

有什么想法吗?

错误消息只是指出 table product_template 中至少有一行包含 product_brand_id [=17= 列中的值 12 ]

但是 table product_brand 中没有相应的行,其中列 id 包含值 12

Key (product_brand_id)=(12) 关联外键的 source 列,而不是目标列。

简单来说,您的 ALTER 语句中提供的 FOREIGN KEY(product_brand_id) 的 不存在于源代码中 (product_brand) table.