[英]one-to-one relationship in database
Suppose that I have a table users
, with a PK id_user
. 假设我有一个表
users
,带有PK id_user
。
I also have an identifying relationship between the table users
and the table employer
. 我还在表
users
和表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? 我可以在表
employer
使用PK id_user
作为外键,也可以在此表中使用PK(具有唯一约束)?
In this case, the employer only have a worker and a worker only have an employer. 在这种情况下,雇主只有一个工人,一个工人只有一个雇主。
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. 更长的答案:根据我的经验,我每次制作的每1对1都会被扩展为1对多或多对多,因为用户的要求可以更好地理解。 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. 在发生这种情况之后,我做了一点,深入研究为什么1对1似乎有意义,并且总是发现它没有。 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.
为了避免一对一的表格,我为自己制定了一个经验法则,因为它们通常表明对要求的理解不完整。
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.
如果你完全确定它是一对一的关系,我不明白为什么你使用2个表而不是一个表。 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.
真正的一对一关系是例如电话号码或电子邮件地址,并且通常它们与所有者一起存储,而不是存储在单独的表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.