子表的主键作为Oracle父表中的外键

时间:2018-10-05 08:44:11

标签: sql oracle oracle11g

我有两个表:

商店

(PK: StoreID)

商店是整体父级,

产品

 Product (PK: ProductID, FK: StoreID)

是孩子。

我受困于一个要求,其中应用程序主键产品ID 应该是表 Store 中的外键。不知道这是否行得通。我已经从带有Oracle后端的自定义框架中尝试了此方法,但这种方法无法按预期工作。

注意:我无法更改架构。

1 个答案:

答案 0 :(得分:0)

我无法完全理解您的问题,但是在两个表之间可能有多个引用。例如:

create table store (
  storeid number(6) primary key not null,
  name varchar2(20) not null,
  last_productid number(6) not null -- not yet a FK, but later it is.
);

create table product (
  productid number(6) primary key not null,
  name varchar2(50) not null,
  storeid number(6) not null,
  constraint fk1 foreign key (storeid) references store (storeid)
);

alter table store add
  constraint fk2 foreign key (last_productid) references product (productid);

您要添加(要添加?)的列last_productid有点棘手。您有两种选择:

  • 它不能为空。当您希望每个商店始终具有last_productid时,就会发生这种情况。您需要将其声明为DEFERRABLE才能插入商店和第一个产品。

  • 它可以为空。然后,一些商店将指向一种产品,而其他商店则不会。这是简单的情况,因为您可以轻松地插入/更新store表。

相关问题