You can always enforce this rule at the app level. However, I'm always distrusful of the apps (since they are full of bugs all the time), so I personally prefer to enforce the rules at the database level, whenever possible.
It's a bit more startup work but saves you a lot of time later on, since it prevents data corruption issues from the start.
You can do:
create table buildings (
building_id int primary key not null
);
create table floors (
building_id int not null references buildings (building_id),
floor_id int not null,
floor_nr int,
primary key (building_id, floor_id)
);
create table glasses (
building_id int not null references buildings (building_id),
glass_id int not null,
glass_price int,
primary key (building_id, glass_id)
);
create table floor_glasses (
building_id int not null,
floor_id int not null,
glass_id int not null,
primary key (building_id, floor_id, glass_id),
foreign key (building_id, floor_id) references floors (building_id, floor_id),
foreign key (building_id, glass_id) references glasses (building_id, glass_id)
);
The key concept is in the last table. There's only one column building_id
that is used in two foreign keys references. This reference sharing ensures the floors and glasses referenced in the last table always belong to the same building.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…