在这种情况下如何确定外键放置在哪里?
如果我有两个表 - 登录名和用户,如下所示:
Logins
LoginIdNo
UserIdNo
HashedPassword
Users
UserIdNo
LoginIdNo
Username
每个登录名“有一个用户”,每个用户“有一个登录名”,但哪个“属于”哪个?
这只是一个判断,还是有一个明确的公式来确定外键应该驻留在哪里?
If I have two tables - Logins and Users, as follows:
Logins
LoginIdNo
UserIdNo
HashedPassword
Users
UserIdNo
LoginIdNo
Username
Each login "has a user" and each user "has a login" but which "belongs to" which?
Is it simply a judgment call or is there a clearcut formula for determining where the foreign key should reside?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一对一的关系。 在这些情况下,放置外键的位置可能由可选性决定。
您将其分成两个实体有什么特殊原因吗? 我不太喜欢一对一映射,尤其是像 JPA 这样的 ORM,它们很难实现(如果您使用一个映射的主键作为另一个映射的外键)。
在您的系统中,登录名和用户之间有什么区别?
如果每次用户登录时都会发生登录(即,这是用户活动的审计跟踪),那么用户和登录之间就有一对多的关系,并且登录应该使用 UserID 外键。
但在这种情况下,用户名位于一个表中,密码位于另一个表中,并且两者之间存在一对一的关系,您必须询问为什么将它们分开。
This is a one-to-one relationship. Where you put the foreign key is probably decided by optionality in those cases.
Is there any particular reason you've split this into two entities? I'm not a huge fan of one-to-one mappings, particularly on ORMs like JPA where they're awkward to implement (if you use the primary key from one as the foreign key to another).
What, in your system, is the difference between a Login and a User?
If Login were to happen each time a user logins in (ie it's an audit trail of user activity) then you have a one-to-many relationship between User and Login and Login should use a UserID foreign key.
But in this case where the username is in one table and the password is in another and there's a one-to-one relationship betwene the two you have to ask why they're separated.
由于登录永远不会与多个用户关联(反之亦然),因此如何定义关系(以及放置外键的位置)是一个任意决定。 除非您还打算添加其他属性(Firleds)或使用角色,否则简单地定义它可能会更简单,如下所示:
Since a Login will never be associated with more than one User (and vice-versa), it is an arbitrary decision of how you define the relationship (and therefore where you place the Foreign Key). Unless you are also going to add other attributes (Firleds) or use Roles, it might be simpler to simply define it like so: