【发布时间】:2010-09-29 11:06:36
【问题描述】:
在解释命令的输出中,我发现了两个术语“序列扫描”和“位图堆扫描”。有人能告诉我这两种扫描有什么区别吗? (我正在使用 PostgreSql)
【问题讨论】:
-
简单地说,“seq scan”不使用索引(通常较慢),所有其他扫描都尝试使用表中定义的索引。
标签: optimization postgresql query-optimization sql-execution-plan
在解释命令的输出中,我发现了两个术语“序列扫描”和“位图堆扫描”。有人能告诉我这两种扫描有什么区别吗? (我正在使用 PostgreSql)
【问题讨论】:
标签: optimization postgresql query-optimization sql-execution-plan
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)
我们可以这样理解:
[是的,这些查询计划很愚蠢,但那是因为我们没有分析test如果我们分析了它,它们都是顺序扫描,因为有5个小行]
【讨论】: