简体   繁体   中英

Is this actually a one-to-many relationship?

I have three tables in my PostgreSQL database:

User - Contains a username and password
MaleProfile - Contains information related to each male user
FemaleProfile - Contains information related to each female user

Initially, instead of having separate MaleProfile and FemaleProfile tables, I had a single Profile table. In that situation, I would have had a one-to-one relationship between the User table and the Profile table. But I've since decided that I really need separate profile tables for men versus women. In this new situation, each record in the User table must map to one and only one record in either the MaleProfile table or the FemaleProfile table (but not both). From the other direction, each record in the MaleProfile table maps to one and only one record in the User table. The same holds true for each FemaleProfile record.

Strictly speaking, the relationship between the User table and each of the profile tables is one to zero-or-one. But are these relationships essentially just one-to-many relationships in the sense that "many" in this case means just zero or one (but not more than one)? If so, would I express them as you would any one-to-many relationship by creating a foreign key column in the MaleProfile table and in the FemaleProfile table, each of which points to the PK column in the User table? Would I need to add any additional constraints to the profile tables to maintain referential integrity?

Thank you.

Just make sure the referencing column in your male/female tables has a uniqueness constraint on it as well as a foreign key constraint. This is a 1-to-1/0 relationship, not 1-to-many.

CREATE TABLE MaleProfile
 (UserId INT NOT NULL PRIMARY KEY
 REFERENCES "User" (UserId));

I believe that you should put the employeeID number in the profile tables and enforcing a unique constraint in those tables. Although I can't really think of how to keep someone from having both a male and female entry, I believe that this way is the way to go.

Check out https://stackoverflow.com/a/669015/1504882 to see a similar situation to yours, but instead with different types of employees.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM