-1 .执行计划,For best results:

EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON)

 0. 可视化执行计划

访问 https://explain.dalibo.com/ 网站

 

分析执行计划 - postgresql 执行计划  - 嵌套查询_执行计划

 

 

1. nested loop join:

对左表中找到的每一行都要扫描右表一次。

这种策略最容易实现但是可能非常耗时

(不过,如果右表可以通过索引扫描,这将是一个不错的策略。因为可以用左表当前行的值来作为右表上索引扫描的键)。

参考:(2条消息) PostgreSQL表连接 nestloop/hash/merge join详解_Focus on PostgreSQL-

2. 例子:–nested loop join:

nl连接大致过程为:1、t2表进行扫描, 过滤条件info = ‘bill’;

2、t2表根据过滤条件输出的中间结果, 每一条中间结果, t1表都根据索引idx_t1_id扫一遍, 过滤条件id= t2.id。
bill@bill=>explain select * from t2 join t1 on (t1.id=t2.id) where t2.info='bill';

                                QUERY PLAN                                 
---------------------------------------------------------------------------
 Nested Loop  (cost=0.29..1793.92 rows=1 width=26)
   ->  Seq Scan on t2  (cost=0.00..1791.00 rows=1 width=13)
         Filter: (info = 'bill'::text)
   ->  Index Scan using idx_t1_id on t1  (cost=0.29..2.91 rows=1 width=13)
         Index Cond: (id = t2.id)
(5 rows)

 

用一个例子来演示会更加清晰