问题描述
假设我有一些 Alpha 的东西,它们可能会也可能不会 或 相关 Bravo 或 Charlie 的东西.
Let's say I've got Alpha things that may or may not be or be related to Bravo or Charlie things.
这些是一对一的关系:没有 Alpha 会与多个 Bravo 相关.没有一个 Bravo 会与多个 Alpha 相关.
These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha.
我有几个目标:
- 一个易于学习和使用的系统维护.
- 在我的内部强制执行数据完整性数据库.
- 匹配的架构现实世界的逻辑组织我的数据.
- 我的类/对象可以很好地映射到的编程数据库表(à la Linq to SQL)
- 快速读写操作
- 有效利用空间(很少有空字段)
我有三个想法…
I've got three ideas…
PK = primary key
FK = foreign key
NU = nullable
一张表有很多 nullalbe 字段(平面文件)…
One table with many nullalbe fields (flat file)…
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU BravoOne
NU BravoTwo
NU BravoThree
NU CharlieOne
NU CharlieTwo
NU CharlieThree
许多表的 nullalbe 字段为零…
Many tables with zero nullalbe fields…
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
Bravos
--------
FK PK AlphaId
BravoOne
BravoTwo
BravoThree
Charlies
--------
FK PK AlphaId
CharlieOne
CharlieTwo
CharlieThree
两者的最佳(或最差):许多表的大量 nullalbe 外键…
Best (or worst) of both: Lots of nullalbe foreign keys to many tables…
Alphas
--------
PK AlphaId
AlphaOne
AlphaTwo
AlphaThree
NU FK BravoId
NU FK CharlieId
Bravos
--------
PK BravoId
BravoOne
BravoTwo
BravoThree
Charlies
--------
PK CharlieId
CharlieOne
CharlieTwo
CharlieThree
如果 Alpha 必须是 Bravo 或 Charlie,但不能同时是两者怎么办?
What if an Alpha must be either Bravo or Charlie, but not both?
如果 Alphas 不仅可以是 Bravos 和 Charlies,还可以是 Deltas、Echos、Foxtrots 或 Golfs 等中的任何一种会怎样?
What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc…?
这是问题的一部分:哪种数据库架构最适合我的导航?
推荐答案
如果你希望每个 Alpha 只与一个 Bravo 相关,我会投票支持使用组合 FK/PK 的可能性:
If you want each Alpha to be related to by only one Bravo I would vote for the possibility with using a combined FK/PK:
Bravos
--------
FK PK AlphaId
BravoOne
BravoTwo
BravoThree
这样一来,只有一个 Bravo 可能会提到您的 Alpha.
This way one and only one Bravo may refer to your Alphas.
如果 Bravos 和 Charlies 必须互斥,最简单的方法可能是创建一个鉴别器字段:
If the Bravos and Charlies have to be mutually exclusive, the simplest method would probably to create a discriminator field:
Alpha
--------
PK AlphaId
PK AlphaType NOT NULL IN ("Bravo", "Charlie")
AlphaOne
AlphaTwo
AlphaThree
Bravos
--------
FK PK AlphaId
FK PK AlphaType == "Bravo"
BravoOne
BravoTwo
BravoThree
Charlies
--------
FK PK AlphaId
FK PK AlphaType == "Charlie"
CharlieOne
CharlieTwo
CharlieThree
通过这种方式,AlphaType 字段会强制记录始终只属于一个子类型.
This way the AlphaType field forces the records to always belong to exactly one subtype.
这篇关于在 SQL 中处理一对一关系的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!