postgres键不存在于表约束中

时间:2017-09-19 09:49:17

标签: postgresql foreign-keys postgresql-9.5

在Postgres 9.5中尝试ALTER 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;

返回错误

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

我很困惑为什么postgres试图找到product_brand.product_brand_id,当fkey从product_template.product_brand_idproduct_brand.id

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

错误消息只是表明表product_template中至少有一行包含12列中的值product_brand_id

但表product_brand中没有相应的行id列包含值12

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

答案 1 :(得分:0)

简单来说,ALTER语句中提供的FOREIGN KEY (product_brand_id)不在源(product_brand)表中