PostgreSQL的查询语句的连接方式与查询计划比较--多表连接(三)

来源:互联网 发布:淘宝店铺转让靠谱吗 编辑:程序博客网 时间:2024/05/20 06:08
续:
PostgreSQL的查询语句的连接方式与查询计划比较--多表连接(一)
PostgreSQL的查询语句的连接方式与查询计划比较--多表连接(二)

 

--step8:在表上执行完毕analyze后,比较查询优化器根据真实数据得到的查询计划,如下例比较了step3的查询计划

test=# analyze;

ANALYZE

test=# explain select * from A, B, C, D;

                                QUERY PLAN

--------------------------------------------------------------------------

 Nested Loop  (cost=0.00..5.61 rows=81 width=48)

   ->  Nested Loop  (cost=0.00..3.56 rows=27 width=36)

         ->  Nested Loop  (cost=0.00..2.18 rows=9 width=24)

               ->  Seq Scan on a  (cost=0.00..1.03 rows=3 width=12)

               ->  Materialize  (cost=0.00..1.04 rows=3 width=12)

                     ->  Seq Scan on b  (cost=0.00..1.03 rows=3 width=12)

         ->  Materialize  (cost=0.00..1.04 rows=3 width=12)

               ->  Seq Scan on c  (cost=0.00..1.03 rows=3 width=12)

   ->  Materialize  (cost=0.00..1.04 rows=3 width=12)

         ->  Seq Scan on d  (cost=0.00..1.03 rows=3 width=12)

(10 rows)

分析:

1)   setp3比,查询计划没有本质变化,只是数字有些变化

 

--step9:在表上执行完毕analyze后,比较查询优化器根据真实数据得到的查询计划,如下例比较了step4的查询计划

test=# analyze;

ANALYZE

test=# explain select * from A, B, C, D where A.c1=B.c1 and B.c1=C.c1 AND C.c1=D.c1;

                                QUERY PLAN

--------------------------------------------------------------------------

 Nested Loop  (cost=1.07..4.25 rows=1 width=48)

   Join Filter: (a.c1 = d.c1)

   ->  Nested Loop  (cost=1.07..3.19 rows=1 width=36)

         Join Filter: (a.c1 = c.c1)

         ->  Hash Join  (cost=1.07..2.12 rows=1 width=24)

               Hash Cond: (a.c1 = b.c1)

               ->  Seq Scan on a  (cost=0.00..1.03 rows=3 width=12)

               ->  Hash  (cost=1.03..1.03 rows=3 width=12)

                     ->  Seq Scan on b  (cost=0.00..1.03 rows=3 width=12)

         ->  Seq Scan on c  (cost=0.00..1.03 rows=3 width=12)

   ->  Seq Scan on d  (cost=0.00..1.03 rows=3 width=12)

(11 rows)

分析:

1)   连接条件与setp4比,查询计划有较大变化;step3采用了归并连接(mergejoin)算法,而本查询计划采用了嵌套循环(Nested Loop

2)   原因是执行了analyze后,查询优化器认为,每个表上没有太多数据,不排序,更能高效得到结果(每个表只有3条元组,在一个页面完全就能保存,完全不用额外的IO

3)   这说明表的数据量也影响着如何生成查询计划

4)   可在执行了analyze后,把step5step7重新执行一遍,观察查询计划的变化(变化与本例类似)

5)   执行了analyze后,实质是把pg_class上的属性(如元组个数)按实际情况进行了修订,如下:

test=# select relname,relpages,reltuples from pg_class where relname='a' or reln

ame='b' or relname='c' or relname='d';

 relname | relpages | reltuples

---------+----------+-----------

 a       |        1 |         3

 b       |        1 |         3

 c       |        1 |         3

 d       |        1 |         3

(4 rows)

0 0
原创粉丝点击