create table house (
id serial primary key
);
create table family (
id serial primary key
);
create table house_family (
house_id integer,
family_id integer,
primary key (house_id, family_id),
foreign key (house_id) references house (id),
foreign key (family_id) references family (id)
);
create table person (
id serial primary key,
family_id integer,
house_id integer,
foreign key (house_id, family_id) references house_family (house_id, family_id)
);
insert into house values (1),(2),(3);
insert into family values (1),(2),(3);
insert into house_family values (1,1),(2,2),(3,3);
insert into person (family_id, house_id) values (1,1),(1,1);
select * from house;
id
----
1
2
3
select * from family;
id
----
1
2
3
select * from house_family;
house_id | family_id
----------+-----------
1 | 1
2 | 2
3 | 3
select * from person;
id | family_id | house_id
----+-----------+----------
5 | 1 | 1
6 | 1 | 1
现在,如果您尝试将来自 family_id 2 的人插入同一个 house_of family_id 1 中:
insert into person (family_id, house_id) values (2,1);
ERROR: insert or update on table "person" violates foreign key constraint "person_house_id_fkey"
DETAIL: Key (house_id, family_id)=(1, 2) is not present in table "house_family".