如何根据条件运行给定的选择语句?
如果条件(来自 table_A)为真,则从 table_B 中选择,否则从 table_C 中选择。 Tables 没有公共列。
像这样的东西
select case when table_A.flag=true then
(select * from table_B )
else
(select * from table_C )
end
from table_A where ...
上面的当然会失败:more than one row returned by a subquery used as an expression
回答1
由于列相同,您可以使用 UNION
。就像是:
SELECT *
FROM Table_B
WHERE (SELECT flag FROM Table_A) = true
UNION ALL
SELECT *
FROM Table_C
WHERE (SELECT flag FROM Table_A) <> true
我在这里假设 Table_A
只有一行,但是您可以调整 WHERE
条件中的子查询以获取 flag
但是您需要它。
基本思想是您设置两个条件,以便一次只有一个为真(基于您的 flag
)。因此,即使它是 UNION
,也只有一部分查询会返回结果,而您最终会得到 Table_B
或 Table_C
。