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

时间:2015-10-15 10:38:29

标签: postgresql conditional 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

2 个答案:

答案 0 :(得分:2)

您可以使用类似条件联合的内容:

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

答案 1 :(得分:0)

CREATE OR replace FUNCTION fnn ()
RETURNS setof t1 AS $$
DECLARE sql TEXT;
BEGIN
    SELECT CASE 
            WHEN max < 10
                THEN 'select ob1, ob2, istart, iend  from t1'
            WHEN max >= 50
                THEN ' select ob1, ob2, istart, iend  from t2;'
            WHEN max > 10
                THEN ' select ob1, ob2, istart, iend  from t3;'
            END AS qry
    INTO sql
    FROM itable;
    RETURN QUERY
    EXECUTE (sql);
END $$
LANGUAGE plpgsql

用法:

select * from fnn()

DO $$
DECLARE sql TEXT;
BEGIN
    SELECT CASE 
            WHEN max < 10
                THEN 'select ob1, ob2, istart, iend  from t1'
            WHEN max >= 50
                THEN ' select ob1, ob2, istart, iend  from t2;'
            WHEN max > 10
                THEN ' select ob1, ob2, istart, iend  from t3;'
            END AS qry
    INTO sql
    FROM itable;
    DROP TABLE IF EXISTS t;
    EXECUTE ('create temp table t as ' || sql);
END $$;

select * from t;