我有一个继承模式,它遵循Table Per Type模式:
Harvesters
harvester_id | description
Harvester_A
harvester_id | propertyA_1 | propertyA_2
Harvester_B
harvester_id | propertyB_1 | propertyB_2
其中 Harvester_A.harvester_id 和 Harvester_B.harvester_id 是引用 Harvesters.harvester_id 的外键。
我有第四张桌子:
Equipment_Set
equipment_set_id | ... | harvester_id
Equipment_Set.harvester_id 是 Harvesters.harvester_id 的外键。
如何在不事先知道我想要哪个子类的情况下获取特定子类的属性?即我有一些Equipment_Set,并希望获得有关其harvester_id的特定Harvester_A或Harvester_B属性,具体取决于它是哪个子类,但事先不知道它是哪一个。
答案 0 :(得分:0)
将所有表与外连接放在一起(在结果中,所有'错误'列都将为NULL):
CREATE VIEW Harversters_A_or_B AS
SELECT harvester_id,
description,
propertyA_1,
propertyA_2,
propertyB_1,
propertyB_2
FROM Harvester
LEFT JOIN Harvester_A USING (harvester_id)
LEFT JOIN Harvester_B USING (harvester_id);
或者使用compound query将所有属性放入相同的列中(所有'错误'连接都不会返回任何行):
CREATE VIEW Harversters_A_or_B AS
SELECT harvester_id,
description,
propertyA_1 AS property1,
propertyA_2 AS property2,
'A' AS type
FROM Harvester
JOIN Harvester_A USING (harvester_id)
UNION ALL
SELECT harvester_id,
description,
propertyB_1,
propertyB_2,
'B'
FROM Harvester
JOIN Harvester_B USING (harvester_id);