如何理解postgres EXPLAIN输出

时间:2017-04-01 08:02:26

标签: sql postgresql explain

EXPLAIN SELECT a.name, m.name FROM Casting c JOIN Movie m ON c.m_id = m.m_id JOIN Actor a ON a.a_id = c.a_id AND c.a_id < 50;

输出

                                                                  QUERY PLAN                                                                  
----------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=26.20..18354.49 rows=1090 width=27) (actual time=0.240..5.603 rows=1011 loops=1)
   ->  Nested Loop  (cost=25.78..12465.01 rows=1090 width=15) (actual time=0.236..4.046 rows=1011 loops=1)
         ->  Bitmap Heap Scan on casting c  (cost=25.35..3660.19 rows=1151 width=8) (actual time=0.229..1.059 rows=1011 loops=1)
               Recheck Cond: (a_id < 50)
               Heap Blocks: exact=989
               ->  Bitmap Index Scan on casting_a_id_index  (cost=0.00..25.06 rows=1151 width=0) (actual time=0.114..0.114 rows=1011 loops=1)
                     Index Cond: (a_id < 50)
         ->  Index Scan using movie_pkey on movie m  (cost=0.42..7.64 rows=1 width=15) (actual time=0.003..0.003 rows=1 loops=1011)
               Index Cond: (m_id = c.m_id)
   ->  Index Scan using actor_pkey on actor a  (cost=0.42..5.39 rows=1 width=20) (actual time=0.001..0.001 rows=1 loops=1011)
         Index Cond: (a_id = c.a_id)
 Planning time: 0.334 ms
 Execution time: 5.672 ms
(13 rows)

我想了解查询规划器的工作原理?我能够理解它选择的过程,但我不明白为什么? 有人可以根据查询选择性和成本模型或任何影响选择的参数来解释这些查询中的查询优化器选择(选择查询处理算法,连接顺序)吗? 还有为什么在索引扫描后使用Recheck Cond?

1 个答案:

答案 0 :(得分:1)

为什么必须有位图堆扫描有两个原因:

  • PostgreSQL必须检查找到的行是否对当前事务可见。请记住,PostgreSQL会在表中保留旧行版本,直到VACUUM删除它们为止。此可见性信息不存储在索引中。

  • 如果work_mem不足以包含每个表行一位的位图,PostgreSQL每个表页使用一位,这会丢失一些信息。 PostgreSQL需要检查有损块,看看块中哪些行确实满足条件 您可以在使用EXPLAIN (ANALYZE, BUFFERS)时看到此信息,然后PostgreSQL会显示是否存在有损匹配,请参阅this example on rextester

    ->  Bitmap Heap Scan on t  (cost=177.14..4719.43 rows=9383 width=0)
                               (actual time=2.130..144.729 rows=10001 loops=1)
          Recheck Cond: (val = 10)
          Rows Removed by Index Recheck: 738586
          Heap Blocks: exact=646 lossy=3305
          Buffers: shared hit=1891 read=2090
          ->  Bitmap Index Scan on t_val_idx  (cost=0.00..174.80 rows=9383 width=0)
                                              (actual time=1.978..1.978 rows=10001 loops=1)
                Index Cond: (val = 10)
                Buffers: shared read=30
    

我无法在这个答案中解释整个PostgreSQL优化器,但它的作用是尝试所有可能的方法来计算结果,估计每个成本的成本并选择最便宜的计划。

要估计结果集的大小,它会使用对象定义和表统计信息,其中包含有关列值分布方式的详细数据。

然后计算它将按顺序和随机访问(I / O成本)读取的磁盘块数,以及它将需要处理多少个表和索引行以及函数调用(CPU成本)总计。可以配置总计中每个组件的权重。

通常,最佳计划是通过首先应用最具选择性的条件来尽快减少结果行数。在你的情况下,这似乎是casting.a_id < 50

如果外部(EXPLAIN输出中的上部)表中的行数很小,则通常首选嵌套循环连接。