表格中有这个字段:
room_id INT NOT NULL CONSTRAINT room_id_ref_room REFERENCES room
我有两个房间的三个2桌:standard_room
和family_room
如何做这样的事情:
room_id INT NOT NULL CONSTRAINT room_id_ref_room REFERENCES standard_room or family_room
我的意思是,room_id
应该引用 standard_room
或 family_room
。
是否可以这样做?
答案 0 :(得分:14)
这是我一直在使用的模式。
CREATE TABLE room (
room_id serial primary key,
room_type VARCHAR not null,
CHECK CONSTRAINT room_type in ("standard_room","family_room"),
UNIQUE (room_id, room_type)
);
CREATE_TABLE standard_room (
room_id integer primary key,
room_type VARCHAR not null default "standard_room",
FOREIGN KEY (room_id, room_type) REFERENCES room (room_id, room_type),
CHECK CONSTRAINT room_type = "standard_room"
);
CREATE_TABLE family_room (
room_id integer primary key,
room_type VARCHAR not null default "family_room",
FOREIGN KEY (room_id, room_type) REFERENCES room (room_id, room_type),
CHECK CONSTRAINT room_type = "family_room"
);
即,'子类'通过类型descriminator列指向超类(使得指向的基类具有正确的类型,并且超类的主键与子类相同。