postgresql - 根据另一个查询返回的条件在 postgres 中触发不同的查询

标签 postgresql conditional-statements postgresql-9.2

根据一个 sql 查询返回的结果,我必须决定调用哪个 SQL 查询。可能吗?

下面是一个演示:

select start, end, max from table.
If max < 10
 select ob1, ob2, start, end from t1
if max >=10 and < 50
 select ob1, ob2, start, end from t2
if max >= 50
 select ob1, ob2, start, end from t2

最佳答案

您可以使用类似条件联合的东西:

select ob1, ob2, q2."start", q2."end"   
from (
    select "start", "end", "max"
    from the_table
    ) q1,
lateral (
        select ob1, ob2, "start", "end"
        from t1 
        where "max" < 10 
    union
        select ob1, ob2, "start", "end" 
        from t2 
        where "max" >=10 and "max" < 50 
    union
        select ob1, ob2, "start", "end" 
        from t3
        where "max" >= 50 
    ) q2

了解 LATERAL Subqueries在文档中。

在 Postgres 9.2 中,可以使用 with 查询:

with m as (
    select "max"
    from the_table)
select ob1, ob2, q."start", q."end"   
from (
        select ob1, ob2, "start", "end"
        from t1, m 
        where "max" < 10 
    union
        select ob1, ob2, "start", "end" 
        from t2, m 
        where "max" >=10 and "max" < 50 
    union
        select ob1, ob2, "start", "end" 
        from t3, m
        where "max" >= 50
) q

关于postgresql - 根据另一个查询返回的条件在 postgres 中触发不同的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146305/

相关文章:

python - 使用 psycopg2 python 库构建 SQL 动态查询并使用良好的转换类型工具

java - 使用 postgres 和 java 进行 Spark 插入操作

sql - 约束排除不适用于分区表

sql - 如何使用新的 PostgreSQL JSON 数据类型中的字段进行查询?

sql - 将 15 分钟间隔转换为每小时间隔的 Postgres 查询

java - hibernate/Dropwizard : Find or create with @UnitOfWork does not work

vb.net - 在 VB.NET 中选择 Case Fall through with Not Condition

r - 在 R 中编写一个包含 if/else 语句和 rowSums() 的函数,定义如何处理 NA

c - 这个正确的条件有什么问题? :)

postgresql - 将函数参数转换为函数