在PostgreSQL中使用CASE来选择不同的FROM

时间:2016-08-01 09:50:56

标签: postgresql

我尝试创建一个查询,其中结果可以来自两个不同的表,具体取决于第一个表的大小。 甚至可能有类似的东西吗?

SELECT 
    CASE WHEN COUNT(table1.column1) > 5
    THEN
        column1,
        column2,
        column3
        FROM table1
    ELSE
        column1,
        column2,
        column3
        FROM table2
    END

使用此代码,我得到了类似的结果:

ERROR:  syntax error at or near ","
LINE 4:   column1, 

1 个答案:

答案 0 :(得分:4)

with c (c) as (select count(c1) from t)
select c1, c2, c3
from t
where (select c from c) > 5
union all
select c1, c2, c3
from r
where (select c from c) <= 5

相应的列必须属于同一类型。或者换成相同的类型。

WITH clause

UNION clause

相关问题