使用类表继承选择子类属性(每种类型的表)

时间:2016-02-16 20:16:12

标签: sql sqlite inheritance

我有一个继承模式,它遵循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属性,具体取决于它是哪个子类,但事先不知道它是哪一个。

1 个答案:

答案 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);