目前,我正在研究数据库。为此,我创建了一个实体关系模型,但是当涉及到三元运算符时,我在阅读它时遇到了一个小问题。让我们看一下这个例子:
------------- (0|N) (0|N) -------------
| Mother |-----------------x----------------| Father |
------------- | -------------
|
|
|
|
| (1|1)
-------------
| Child |
-------------
这个小型实体关系模型如下所示:
A mother can have 1 to N childs - Okay
A father can have 1 to N childs - Okay
A child has exatcly 1 father and 1 mother - Okay
但也可以说:
A father has N mothers - Not okay
A mother has N fathers - Not okay
所以我理解错了或者这些三元运算符不明显吗?通过此实现,可以创建不一致的数据集。方向对于这些运算符重要吗?还是我必须以其他方式阅读它们?
最佳答案
您的主要实体是人。母亲、父亲和后代是人与人之间的关系。
create table People(
ID int primary key auto_generated,
Sex Char( 1 ) check( Sex in( 'F', 'M' )),
...
);
create unique index UQ_People_Parent on People( ID, Sex );
如果 ID 本身是唯一的,为什么要使 ID 和性别的组合唯一?
create table Parents(
MotherID int,
FemaleFlag char( 1 ) check FemaleFlag = 'F',
FatherID int,
MaleFlag char( 1 ) check MaleFlag = 'M',
constraint FK_Parent_Mother foreign key( MotherID, FemaleFlag )
references People( ID, Sex ),
constraint FK_Parent_Father foreign key( FatherID, MaleFlag )
references People( ID, Sex ),
constraint PK_Parents primary key( MotherID, FatherID )
);
这会建立一个 m-n 交集表。这很好,因为 parent 可以与不同的配偶生 child 。添加旗帜使我们能够强制执行母亲必须是女性而父亲必须是男性的限制。
create table OffSpring(
PersonID int primary key,
MotherID int,
FatherID int,
constraint FK_OffSpring_Parents foreign key( MotherID, FatherID )
references Parents( MotherID, FatherID ),
constraint FK_Offspring_Person foreign key( PersonID )
references People( ID )
);
后代可以是女儿或儿子,因此没有性别差异。
如果我们有 parent 的 ID,并且想要找到他们的后代,我们可以直接将 People 加入 OffSpring 来查找他们,根据需要将 ID 字段添加到 MotherID 字段或 FatherID 字段。如果我们有 OffSpring 的 ID,我们可以直接将 OffSpring 加入到 People 的 MotherID 字段或 FatherID 字段到 ID 字段。 parent 表主要只是为了强制执行:1)母亲和父亲被定义为一对,2)母亲必须是女性,父亲必须是男性。
对于阅读本文的每个人,请不要再发表任何政治正确的性别模糊的废话。这仅用于说明。如果有人想要Parent1和Parent2而不是Mother和Father,并且其中一方或双方是男性或女性,那么就这样设计。
关于database-design - 实体关系模型-三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670599/