Postgres - 是否有准备好的报表支持的观点?

时间:2016-01-15 09:27:21

标签: sql postgresql prepared-statement sql-view

创建视图时,PostgreSQL是否也为相应的查询创建了一个准备好的语句?或者每次访问视图时是否重新生成查询执行计划?

1 个答案:

答案 0 :(得分:3)

不,每次使用视图时都会构建一个查询计划。即使视图与其他表或视图连接(您可以将视图视为一种宏)。只需查看生成的查询计划:

CREATE table one
        ( one_id INTEGER NOT NULL PRIMARY KEY
        , one_text text
        );
INSERT INTO one (one_id,one_text)
SELECT gs, 'one_' || gs::integer
FROM generate_series (0,10,2) gs;

CREATE table two
        ( two_id INTEGER NOT NULL PRIMARY KEY
        , two_text text
        );
INSERT INTO two (two_id,two_text)
SELECT gs, 'two_' || gs::integer
FROM generate_series (0,10,3) gs;

VACUUM ANALYZE one;
VACUUM ANALYZE two;

CREATE VIEW silly_carth AS
SELECT o.one_id, o.one_text
        , t.two_id, t.two_text
FROM one o
CROSS JOIN two t
        ;

EXPLAIN
SELECT * FROM silly_carth;
EXPLAIN
SELECT * FROM silly_carth WHERE one_id = two_id;

结果计划:

                            QUERY PLAN                            
------------------------------------------------------------------
 Nested Loop  (cost=0.00..2.41 rows=24 width=20)
   ->  Seq Scan on one o  (cost=0.00..1.06 rows=6 width=10)
   ->  Materialize  (cost=0.00..1.06 rows=4 width=10)
         ->  Seq Scan on two t  (cost=0.00..1.04 rows=4 width=10)
(4 rows)

                            QUERY PLAN                            
------------------------------------------------------------------
 Hash Join  (cost=1.09..2.21 rows=4 width=20)
   Hash Cond: (o.one_id = t.two_id)
   ->  Seq Scan on one o  (cost=0.00..1.06 rows=6 width=10)
   ->  Hash  (cost=1.04..1.04 rows=4 width=10)
         ->  Seq Scan on two t  (cost=0.00..1.04 rows=4 width=10)
(5 rows)