If I have users, as well as user groups (like a local astronomy group/club), and I want both to have a one to many relationship with street addresses, can I just have 1 address table, and two fk’s so that I don’t have to duplicate the table schema? or is it better practice to just have 2 separate tables, user_addresses & user_group_addresses? Appreciate your input and time, thx!
Share
The design you describe, with two foreign keys, is called an exclusive arc. Only one of the two foreign keys should be populated. It’s pretty awkward to enforce and to use.
For instance, an address must reference one entity, so conceptually the column is mandatory and should be NOT NULL. But you can’t make both columns NOT NULL, because one of them doesn’t pertain to a given address. So they have to be nullable. And then you have to have some other way to prevent both from being NULL, and also prevent both from being non-NULL. MySQL doesn’t support CHECK constraints, so you can write a trigger or else write custom application code to enforce this rule.
What about creating one address table, but reverse the relationship? That is, the Users and Groups tables contain a foreign key reference to the Addresses table instead of the other way around.
The other solution is for both Users and Groups to be dependent on a common supertable, call it "Addressables" or something. Like an interface or abstract class in OO design. Then your addresses can also have a foreign key to Addressables. See examples in other questions I have answered on this subject.
I also cover this problem in more detail in my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming, in the chapter "Polymorphic Associations".