复合主键或单主键
是使用单个主键更好,还是使用复合主键(通常,它们是一个主键和外键的组合)。我有以下示例:
复合主键示例:
AMeta
--- AMetaId - 主键
--- AMetaText
BMeta
--- BMetaId - 主键
--- AMetaID - 表 AMeta 的外键
--- BMetaText
A
--- AId - 主键
--- AMetaId - 表 AMeta 的主键和外键
--- AText
B
--- BId - 主键
--- BMetaId - 表 BMeta 的主键外键
--- AId - 表 A 的主键和外键
--- BText
单主键示例:
AMeta
--- AMetaId - 主键
--- AMetaText
BMeta
--- BMetaId - 主键
--- AMetaId - 表 AMeta 的外键
--- BMetaText
A
--- AId - 主键
--- AMetaId - 表 AMeta 的外键
--- AText
B
--- BId - 主键
--- BMetaId - 表 BMeta 的外键
--- AId - 表 A 的外键
--- BText
哪个数据库设计更好?
Is it better to have a single primary key, or use composite primary keys (usually, they are combination of one primary key and foriegn keys). I have examples below:
Composite Primary Key example:
AMeta
--- AMetaId - Primary Key
--- AMetaText
BMeta
--- BMetaId - Primary Key
--- AMetaID - Foreign Key to Table AMeta
--- BMetaText
A
--- AId - Primary Key
--- AMetaId - Primary Key and Foreign Key to Table AMeta
--- AText
B
--- BId - Primary Key
--- BMetaId - Primary Key Foreign Key to Table BMeta
--- AId - Primary Key and Foreign Key to Table A
--- BText
Single Primary Key example:
AMeta
--- AMetaId - Primary Key
--- AMetaText
BMeta
--- BMetaId - Primary Key
--- AMetaId - Foreign Key to Table AMeta
--- BMetaText
A
--- AId - Primary Key
--- AMetaId - Foreign Key to Table AMeta
--- AText
B
--- BId - Primary Key
--- BMetaId - Foreign Key to Table BMeta
--- AId - Foreign Key to Table A
--- BText
Which is the better Database Design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通常倾向于几乎完全使用单列主键 - 要么有一个好的自然键可用(很少),要么我向表中添加一个代理 INT IDENTITY 键。
我的主要原因是:
I genereally tend to use single-column primary keys almost exclusively - either there is a good natural key available (pretty rarely), or then I add a surrogate INT IDENTITY key to the table.
My main reasons are:
第一个方案没有意义,因为它暗示(并允许)表 B 中可以有多行具有相同的 BId 值但具有不同的 AId 值,并且与列 Bid 没有关联的意义。是去别的地方的 FK 吗?如果是的话,为了什么呢?如果不是,那么是什么产生了它?这是什么意思?
另一方面,第二种方案在逻辑上是一致的,但意味着表 B 中的行可以
BMetaId 并从那里到表
AMeta 使用 TableB.AMetaId,并
BMetaId 到表 BMeta 并从
使用 BMEta.AMetaId 到 AMeta
这真的是您的业务域模型的准确表示吗?
The first scheme makes no sense, because it implies (and allows) that there can be multiple rows in Table B with the same BId value but with different values of AId, and there is no meaning associated with column Bid. Is it a FK to somewhere else? If so, to what? If not, what is generating it ? What does it mean?
The second scheme, on the other hand, is logically consistent, but implies that rows in Table B can be associated with two different rows in Table AMeta,
BMetaId and from there to Table
AMeta using TableB.AMetaId, and
BMetaId to Table BMeta and from
there to AMeta using BMEta.AMetaId
Is this really an accurate representation of your business domain model?