表中的外键快捷键

发布于 2024-12-09 17:22:22 字数 505 浏览 0 评论 0原文

想象一个这样的模式。

NOTE TABLE:            NoteID, Note, DetailedTaskID, .....

DETAILED TASK TABLE:   DetailedTaskID, WorkOrderID, .....

WORKORDER TABLE:       WorkOrderID, ProjectID, .....

PROJECT TABLE:         ProjectID, .....

现在,有了这个模式,假设我想检索与特定项目关联的所有注释,我最终会得到相当多的联接。

IE: Note JOIN DetailedTask JOIN WorkOrder JOIN Project

所以我的问题是,什么时候(如果有的话)适合为表添加“快捷方式”列(在本例中为 ProjectID)?

所以基本上将注释表更改为:NoteID,Note,DetailedTaskID,ProjectID

Imagine a schema as such.

NOTE TABLE:            NoteID, Note, DetailedTaskID, .....

DETAILED TASK TABLE:   DetailedTaskID, WorkOrderID, .....

WORKORDER TABLE:       WorkOrderID, ProjectID, .....

PROJECT TABLE:         ProjectID, .....

Now with this schema lets say I want to retrieve all notes that are associated to a specific project I end up with quite a number of joins.

IE: Note JOIN DetailedTask JOIN WorkOrder JOIN Project

So my question is this, when (if ever) is it appropriate to add a "shortcut" column for a table (in this case ProjectID)?

So basically changing the note table to this: NoteID, Note, DetailedTaskID, ProjectID

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小帐篷 2024-12-16 17:22:22

简短的回答:永远,永远,永远。

更长的答案:仅当:

  1. 您确定 JOIN 的性能不可接受(这很少是真的)。​​

  2. 您确实已经用尽了所有危险性较低的替代方案。

  3. 您愿意承担保持冗余、非规范化信息同步所需的额外工作

  4. 您愿意接受这样一个事实:如果您未能保持同步,您的数据库在技术上可能会返回不正确的结果。

Short answer: Never, ever, ever.

Longer answer: Only when:

  1. You've determined that the performance of the JOINs is unacceptable (which is rarely true).

  2. You've genuinely exhausted all less dangerous alternatives.

  3. You are willing to absorb the extra work involved in keeping the redundant, de-normalized information in sync

  4. You are willing to accept the fact that it then becomes technically possible for your database to return incorrect results if you ever fail to keep things synced up.

百思不得你姐 2024-12-16 17:22:22

你所说的就是所谓的外键关系。它是数据标准化的基础。简而言之,如果注释(即 NoteID)属于项目,则可以将外键关系(ProjectID)添加到注释表中。

这样做的好处是,您可以查询此关系数据,如下所示:

select
  Note.*,
  Project.*
from Note
left join Project
on Note.ProjectId = Project.ProjectId

该查询将生成所有注释以及与其相关的项目数据(如果它是项目的一部分)。

What you're talking about is called a foreign key relationship. It's the basis for Data Normalization. In short, you would add a foreign key relationship (ProjectID) to your Note table if a Note (i.e. NoteID) belongs to a Project.

The benefits of doing this are so that you can query this relational data, like this:

select
  Note.*,
  Project.*
from Note
left join Project
on Note.ProjectId = Project.ProjectId

That query would yield all notes, and project data (if it is part of a project) that is related to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文