[英]Postgresql select from based on condition
How to run a given select statement based on condition?如何根据条件运行给定的选择语句?
If a condition (which comes from table_A) is true then select from table_B otherwise from table_C.如果条件(来自 table_A)为真,则从 table_B 中选择,否则从 table_C 中选择。 Tables have no common column.
表没有公共列。
Something like this像这样的东西
select case when table_A.flag=true then
(select * from table_B )
else
(select * from table_C )
end
from table_A where ...
The above one will fail of course : more than one row returned by a subquery used as an expression
上面的当然会失败:
more than one row returned by a subquery used as an expression
Since the columns are the same, you could use a UNION
.由于列是相同的,您可以使用
UNION
。 Something like:就像是:
SELECT *
FROM Table_B
WHERE (SELECT flag FROM Table_A) = true
UNION ALL
SELECT *
FROM Table_C
WHERE (SELECT flag FROM Table_A) <> true
I'm assuming here that Table_A
has only one row, but you could adjust the subquery in the WHERE
conditions to get the flag
however you need it.我在这里假设
Table_A
只有一行,但您可以调整WHERE
条件中的子查询以获取您需要的flag
。
The basic idea is that you set up the two conditions so that only one of them is true at a time (based on your flag
).基本思想是您设置两个条件,以便一次只有一个条件为真(基于您的
flag
)。 So, even though it is a UNION
, only one part of the query will return results and you either end up with Table_B
or Table_C
.因此,即使它是
UNION
,也只有一部分查询会返回结果,您最终会得到Table_B
或Table_C
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.