Slow query on “UNION ALL” view

后端 未结 8 1895
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 06:20

I have a DB view which basically consists of two SELECT queries with UNION ALL, like this:

CREATE VIEW v AS
SELECT time, etc. FROM t1 /         


        
8条回答
  •  再見小時候
    2021-02-13 07:06

    A possibility would be to issue a new SQL dynamically at each call instead of creating a view and to integrate the where clause in each SELECT of the union query

    SELECT time, etc. FROM t1
        WHERE time >= ... AND time < ...
    UNION ALL
    SELECT time, etc. FROM t2
        WHERE time >= ... AND time < ...
    

    EDIT:

    Can you use a parametrized function?

    CREATE OR REPLACE FUNCTION CallMyView(t1 date, t2 date)
    RETURNS TABLE(d date, etc.)
    AS $$
        BEGIN
            RETURN QUERY
                SELECT time, etc. FROM t1
                    WHERE time >= t1 AND time < t2
                UNION ALL
                SELECT time, etc. FROM t2
                    WHERE time >= t1 AND time < t2;
        END;
    $$ LANGUAGE plpgsql;
    

    Call

    SELECT * FROM CallMyView(..., ...);
    

提交回复
热议问题