【问题标题】:postgres key is not present in table constraint表约束中不存在 postgres 键
【发布时间】:2018-02-28 01:10:30
【问题描述】:

在 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

有什么想法吗?

【问题讨论】:

    标签: postgresql foreign-keys postgresql-9.5


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      product_brand 表中没有对应的行,其中id 列包含值12

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

      【讨论】:

      • 我们不能允许添加外键约束,尽管列中有这样的值在外表中不存在吗?
      • @aagjalpankaj:如果要允许无效数据,请不要添加约束
      • 我必须添加 FK 约束但想忽略现有值,并且约束应该适用于未来值。有什么办法可以实现吗?
      • 不,您要么需要完全删除这些行,要么将 FK 列设置为 NULL
      猜你喜欢
      • 2019-02-20
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多