表中的外键快捷键
想象一个这样的模式。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短的回答:永远,永远,永远。
更长的答案:仅当:
您确定 JOIN 的性能不可接受(这很少是真的)。
您确实已经用尽了所有危险性较低的替代方案。
您愿意承担保持冗余、非规范化信息同步所需的额外工作
您愿意接受这样一个事实:如果您未能保持同步,您的数据库在技术上可能会返回不正确的结果。
Short answer: Never, ever, ever.
Longer answer: Only when:
You've determined that the performance of the JOINs is unacceptable (which is rarely true).
You've genuinely exhausted all less dangerous alternatives.
You are willing to absorb the extra work involved in keeping the redundant, de-normalized information in sync
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.
你所说的就是所谓的外键关系。它是数据标准化的基础。简而言之,如果注释(即 NoteID)属于项目,则可以将外键关系(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:
That query would yield all notes, and project data (if it is part of a project) that is related to it.