Reputation: 969
I have two tables - 1st is place and 2nd is location. Place can have zero or many locations. Place PK is id, and location PK is two component key place_id + id.
In third table (ex. invoice) I could have place which doesn't have any location.
The question is: how to set FK in invoice table?
So, the main problem is that some place can have 0 locations.
Yes, I might to set surrogate PK in location table, and set place_id FK, location_id FK NULL. But, the requirement is that place and location keys are natural (based on company organizational structure). Second idea is to have one to one/many association and put in location id value 0 for place which have zero locations and hide this location in user interface. Actually, then I need to put for every place location 0 (no location).
Thanks.
Upvotes: 1
Views: 199
Reputation: 52107
You should be able to simply "merge" these two FKs together:
CREATE TABLE invoice (
id INT PRIMARY KEY,
place_id INT NOT NULL,
location_id INT NULL,
FOREIGN KEY (place_id) REFERENCES place (id),
FOREIGN KEY (place_id, location_id) REFERENCES location (place_id, id)
);
The DBMS will ignore a FK with at least one NULL:
place_id
is NOT NULL so the first FK will always be in force.location_id
is NULL, the second FK will simply be ignored.You can play with it in this SQL Fiddle.
(In fact, the very existence of natural key is what enables you to do this - if location
had a surrogate key, you could not guarantee that the two FKs point to the same place
.)
In an unlikely case your DBMS treats NULLs in a funny way so a FK with a NULL is not ignored, you can completely separate these two FKs, and use CHECK to ensure they belong to the same location:
CREATE TABLE invoice (
id INT PRIMARY KEY,
place_id INT NOT NULL,
location_place_id INT NULL,
location_id INT NULL,
FOREIGN KEY (place_id) REFERENCES place (id),
FOREIGN KEY (location_place_id, location_id) REFERENCES location (place_id, id),
CHECK (place_id = location_place_id)
);
Upvotes: 2