Slow query on “UNION ALL” view

后端 未结 8 1890
伪装坚强ぢ
伪装坚强ぢ 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:11

    I believe your query is being executed similar to:

    (
       ( SELECT time, etc. FROM t1 // #1... )
       UNION ALL
       ( SELECT time, etc. FROM t2 // #2... )
    )
    WHERE time >= ... AND time < ...
    

    which the optimizer is having difficulty optimizing. i.e. it's doing the UNION ALL first before applying the WHERE clause but, you wish it to apply the WHERE clause before the UNION ALL.

    Couldn't you put your WHERE clause in the CREATE VIEW?

    CREATE VIEW v AS
    ( SELECT time, etc. FROM t1  WHERE time >= ... AND time < ... )
    UNION ALL
    ( SELECT time, etc. FROM t2  WHERE time >= ... AND time < ... )
    

    Alternatively if the view cannot have the WHERE clause, then, perhaps you can keep to the two views and do the UNION ALL with the WHERE clause when you need them:

    CREATE VIEW v1 AS
    SELECT time, etc. FROM t1 // #1...
    
    CREATE VIEW v2 AS
    SELECT time, etc. FROM t2 // #2...
    
    ( SELECT * FROM v1 WHERE time >= ... AND time < ... )
    UNION ALL
    ( SELECT * FROM v2 WHERE time >= ... AND time < ... )
    

提交回复
热议问题