数据库中的一对一关系
假设我有一个表 users
,带有 PK id_user
。
我还在表users
和表employer
之间建立了标识关系。我可以使用 PK id_user
作为表 employer
中的外键,也可以用作该表中的 PK(具有唯一约束)?
在这种情况下,雇主只有一个工人,而工人也只有一个雇主。
Suppose that I have a table users
, with a PK id_user
.
I also have an identifying relationship between the table users
and the table employer
. I can use the PK id_user
as foreign key in the table employer
and also as PK (with unique constrain) in this table?
In this case, the employer only have a worker and a worker only have an employer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短回答:是的。当外键也是子表的主键时,它会强制子表成为一对一。
更长的答案:根据我的经验,我所做的每一个一对一后来都扩展到了一对多或多对多,因为用户的需求得到了更好的理解。示例:您最终需要雇主的历史记录,因此突然间您有了从个人到雇主的多对多的有效日期。
这种情况发生几次后,我特意深入研究了一对一似乎有意义的原因,但总是发现事实并非如此。以至于我为自己制定了一条经验法则,以避免使用一对一的表格,因为它们通常表明对需求的理解不完整。
Short answer: Yes. When a foreign key is also the primary key of the child table it forces it into a one-to-one.
Longer answer: in my experience every 1-to-1 I've every made has been expanded later into a 1-to-many or many-to-many, as the users' requirements are better understood. Example: You end up needing a history of employers, so suddenly you have a many-to-many from persons to employers with effective dates.
After this happened a few times I made it a point to dig into the reasons why a 1-to-1 seemed to make sense, and always found it did not. So much so that I made a rule of thumb for myself to avoid 1-to-1 tables, as they usually indicate an incomplete understanding of requirements.
主键是特殊的唯一键。在这种情况下,我不会将工人链接到雇主表中,因为通常雇主有不止一名工人。如果您绝对确定这是一对一的关系,我不明白为什么您使用 2 个表,而不是一个。意思是,将雇主字段添加到工人表中。真正的一对一关系是例如电话号码或电子邮件地址,通常它们与所有者一起存储,而不是存储在单独的表中。
Primary keys are special unique keys. In this case I would not link worker in the employers table as typically an employer has more then one worker. If you're absolutely sure it is a one-one relation, I do not see why you use 2 tables, instead of one. Meaning, add the employer fields to the worker table. A real one-one relation is for example a phone number or email address and typically they are stored with the owner, not in a seperate table.