We need a solution to the following problem which makes sense an also follows best practices without making things to complicated.
We have 3 tables which need to be linked, Sector, Location and Company.
ie: A Company “Bobs B&B” is in Sector “Accommodation” which is in Location “New York”.
For hotel groups we could have a single company in multiple sectors across multiple locations.
So we decided to simply create a “CompanySectorLocation” table which has 3 primary keys linking the 3 tables:
CompanySectorLocation
CompanyID (PK FK)
SectorID (PK FK)
LocationID (PK FK)
The curved ball here is that the Location is not required.
ie: “Protea Hotels” is active in the “Accomodation” sector leaving the location as NULL.
My developer is very much against having a table that allows for a NULL FK. His suggestion is to create another table called CompanySector which will deal with the links between Company and Sector where Location is not defined.
CompanySector
CompanyID (PK FK)
SectorID (PK FK)
My issue with this is that we will have to maintain 2 tables with effectively duplicate data in them.
What is the best way to do this?
I would create a separate table. I have nothing against NULL FK’s (many people do), but having one table means you’re going to have duplicate data anyway. E.g. if Bob’s B&B opens up a branch in California, you’ll have duplicate entries in the table specifying the relationship between ‘Bob’s B&B’ and ‘Accommodation’. Having a single table also means you’ll have to include
DISTINCTin any join on this table only involving the CompanyID and SectorID columns (which seems likely if LocationID is nullable).Effectively you will have two many-to-many relationships:
and
It makes sense to use two linking tables to model two different relationships. If you need all 3 entries in one table (for convenience), you can always create an indexed view.