【问题标题】:Primary Key of Child Table as Foreign Key in Parent Table in OracleOracle中子表的主键作为父表的外键
【发布时间】:2018-10-05 08:44:10
【问题描述】:

我有两张桌子:

商店

(PK: StoreID)

Store 是整体父级和

产品

 Product (PK: ProductID, FK: StoreID)

是个孩子。

我遇到了一个要求,应用程序 Primary Key ProductID 应该是表 Store 中的外键。不确定这是否会奏效。我已经从带有 Oracle 后端的自定义框架中尝试过这个,但是没有按预期工作。

注意:我无法更改架构。

【问题讨论】:

  • 那你有什么问题?
  • 基本上,问题是这种方法在 Oracle 中是否可行,因为当我尝试这样做时它不起作用(可能是我这边出错了)
  • 你应该展示你实际尝试了什么以及它是如何失败的,以便其他人可以看到它是否是...你这边的错误并在这种情况下为你提供帮助。跨度>
  • “我遇到了这样一个要求:应用程序的主键 ProductID 应该是表 Store 中的外键。” 那么每个商店只能有一个产品? (requirements 文档很少会识别外键并指示它们的存储位置。您确定这是一项要求吗?)

标签: sql oracle oracle11g


【解决方案1】:

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

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 表。

【讨论】:

  • 是的,'last_productid' 我想添加为 Store 的外键。它肯定不会为空。需要看看如何在框架上实现选项 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-10
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 2014-05-05
相关资源
最近更新 更多