为什么我不能添加从父 table 的复合键引用的外键?

Why can't I add a foreign key that references from a composite key from the parent table?

我有一个 table,它有 2 个同时是主键和外键的键,它们还引用了另一个 table。

CREATE TABLE public."restaurantProduct"
(
  "restaurantId" bigint NOT NULL,
  "productId" bigint NOT NULL,
  CONSTRAINT "restaurantProduct_pkey" PRIMARY KEY ("restaurantId", "productId"),
  CONSTRAINT "restaurantProduct_productId_fkey" FOREIGN KEY ("productId")
      REFERENCES public.products ("productId") MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT,
  CONSTRAINT "restaurantProduct_restaurantId_fkey" FOREIGN KEY ("restaurantId")
      REFERENCES public.restaurant ("restaurantId") MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE RESTRICT
)

现在我想创建另一个名为 custOrders 的 table 并使用 restaurantProduct.restaurantId 作为外键,但它给我一个错误 Error: there is no当我已经将 restaurantProduct.restaurantId 指定为主键时,唯一约束匹配给定键的引用表“restaurantProduct”。也无法将 UNIQUE 添加到 restaurantProduct.restaurantId,因为餐厅可以有多种产品。我可以重新设计数据库,但我只是想知道是否有任何方法可以单独使用此设计?

I already have assigned restaurantProduct.restaurantId as a primary key

不,该列不是主键。它是复合主键的一部分。 restaurantProduct table 中可以有多行具有相同的 restaurntId,只要它们具有不同的 productId

I want to create another table called custOrders and use the restaurantProduct.restaurantId as foreign key

如错误消息所述,您不能这样做。但是,您可以将其设为引用 restaurant.restaurantId.

如果您真的想将订单参考设为 restaurantProduct,您将需要两列 - 一列用于 restaurantId,一列用于 productId,然后有一个组合将引用 restaurantProduct.

中的 both 列的外键