分区视图是一种可能的方法。由于您只选择 foo 列,您真的只是通过 INNER JOIN 检查训练表中是否存在一行?此外,您似乎正在尝试在联接中使用 foo 作为别名,但在您的 SELECT 子句中没有以这种方式设置。结果,我在这里猜测您真正想要什么。
另一个问题......训练表集是静态的吗?您是否期望能够添加具有新后缀编号的新表并使其正常工作?
另一种可能的解决方案:
SELECT
foo
FROM
dbo.master m
WHERE
(training_type = '001' AND EXISTS (SELECT * FROM dbo.training_data_001 WHERE foo_id = m.id)) OR
(training_type = '002' AND EXISTS (SELECT * FROM dbo.training_data_002 WHERE foo_id = m.id)) OR
(training_type = '003' AND EXISTS (SELECT * FROM dbo.training_data_003 WHERE foo_id = m.id)) OR
(training_type = '004' AND EXISTS (SELECT * FROM dbo.training_data_004 WHERE foo_id = m.id)) OR
(training_type = '005' AND EXISTS (SELECT * FROM dbo.training_data_005 WHERE foo_id = m.id))
如果你真的想从训练数据表中返回列,那么你可以使用类似的东西:
SELECT
m.id,
COALESCE(t1.my_col, t2.my_col, t3.my_col, t4.my_col, t5.my_col) AS my_col
FROM
dbo.master m
LEFT OUTER JOIN dbo.training_data_001 t1 ON m.training_type = '001' AND t1.foo_id = m.id
LEFT OUTER JOIN dbo.training_data_002 t1 ON m.training_type = '002' AND t2.foo_id = m.id
LEFT OUTER JOIN dbo.training_data_003 t1 ON m.training_type = '003' AND t3.foo_id = m.id
LEFT OUTER JOIN dbo.training_data_004 t1 ON m.training_type = '004' AND t4.foo_id = m.id
LEFT OUTER JOIN dbo.training_data_005 t1 ON m.training_type = '005' AND t5.foo_id = m.id