views:

135

answers:

2

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?

+1  A: 

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:

Users 
    UserIdNo 
    Username
    HashedPassword
Mitch Wheat
+1  A: 

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.

cletus
There are two differences between Login and User that I was thinking of. One is the User table would have many other fields for contact information (address, telephone, etc). While the Logins table would be more sparse data-wise but the table as a whole might undergo some form of encryption independent of my application (not sure exactly how that would be done).
pez_dispenser
Your audit trail example makes a good point. Conversely if there is a requirement for an audit trail on every edit of the user data, perhaps the foreign key would be the LoginId, unless the Login information is also audited - if both User and Login have audit trails I'm not sure how this works - in that case maybe we also need a UserAudit and LoginAudit table?
pez_dispenser
@fraggle: I prefer to think of that distinction as Person and User, which is a reasonable modelling decision. But if you were doing that username and password would probably be on the same entity.
cletus
Yes I agree - Person and User makes sense. But I'm not sure I understand your statement that "if you were doing that username and password would probably be on the same entity". Do you mean that username and password would both exist in the User entity in that scenario?
pez_dispenser