61

在解释命令的输出中,我发现了两个术语“序列扫描”和“位图堆扫描”。有人能告诉我这两种扫描有什么区别吗?(我正在使用 PostgreSql)

4

1 回答 1

86

http://www.postgresql.org/docs/8.2/static/using-explain.html

基本上,顺序扫描将转到实际行,并从第 1 行开始读取,并继续直到满足查询(这可能不是整个表,例如,在限制的情况下)

位图堆扫描意味着 PostgreSQL 找到了一小部分要获取的行(例如,从索引中),并且将只获取那些行。这当然会有更多的搜索,所以只有当它需要一小部分行时才会更快。

举个例子:

create table test (a int primary key, b int unique, c int);
insert into test values (1,1,1), (2,2,2), (3,3,3), (4,4,4), (5,5,5);

现在,我们可以轻松获得 seq 扫描:

explain select * from test where a != 4

                       QUERY PLAN                        
---------------------------------------------------------
 Seq Scan on test  (cost=0.00..34.25 rows=1930 width=12)
   Filter: (a <> 4)

它进行了顺序扫描,因为它估计它将抢占表的绝大多数;试图做到这一点(而不是大量的、无意义的阅读)将是愚蠢的。

现在,我们可以使用索引:

explain select * from test where a = 4 ;
                              QUERY PLAN                              
----------------------------------------------------------------------
 Index Scan using test_pkey on test  (cost=0.00..8.27 rows=1 width=4)
   Index Cond: (a = 4)

最后,我们可以得到一些位图操作:

explain select * from test where a = 4 or a = 3;
                                  QUERY PLAN                                  
------------------------------------------------------------------------------
 Bitmap Heap Scan on test  (cost=8.52..13.86 rows=2 width=12)
   Recheck Cond: ((a = 4) OR (a = 3))
   ->  BitmapOr  (cost=8.52..8.52 rows=2 width=0)
         ->  Bitmap Index Scan on test_pkey  (cost=0.00..4.26 rows=1 width=0)
               Index Cond: (a = 4)
         ->  Bitmap Index Scan on test_pkey  (cost=0.00..4.26 rows=1 width=0)
               Index Cond: (a = 3)

我们可以这样理解:

  1. 为 a=4 构建我们想要的行的位图。(位图索引扫描)
  2. 为 a=3 构建我们想要的行的位图。(位图索引扫描)
  3. 或将两个位图放在一起 (BitmapOr)
  4. 在表中查找这些行(位图堆扫描)并检查以确保 a=4 或 a=3(重新检查 cond)

[是的,这些查询计划很愚蠢,但那是因为我们没有分析test如果我们分析了它,它们都是顺序扫描,因为有 5 个小行]

于 2009-01-04T08:23:54.073 回答