2012-04-18 83 views
5

我有一个查询,它是使用一个嵌套的循环等连接两个表,TableA和TableB。由于“equi”加入约束,结果中返回的所有行因此将对应于这两个表中每个表的至少一行。但是,根据计划(EXPLAIN ANALYZE),即使在最终结果中返回一行,TableB中的实际行计数也为0。这里的实际行如何计数等于零?为什么我的PostgreSQL计划中的行数为0?

下面是执行计划:

=> explain analyze select p.id, p.title, s.count from products p, stock s where p.id = s.p_id and s.w_id = 6 and p.type = 9 and s.count > 0 order by p.title; 
                  QUERY PLAN               
------------------------------------------------------------------------------------------------------------------------------ 
Sort (cost=42.42..42.42 rows=2 width=36) (actual time=0.198..0.199 rows=1 loops=1) 
    Sort Key: p.title 
    Sort Method: quicksort Memory: 25kB 
    -> Nested Loop (cost=0.00..42.41 rows=2 width=36) (actual time=0.170..0.181 rows=1 loops=1) 
     -> Seq Scan on products p (cost=0.00..9.25 rows=4 width=32) (actual time=0.068..0.106 rows=4 loops=1) 
       Filter: (type = 9) 
     -> Index Scan using stock_pk on stock s (cost=0.00..8.28 rows=1 width=8) (actual time=0.015..0.015 rows=0 loops=4) 
       Index Cond: ((w_id = 6) AND (p_id = p.id)) 
       Filter: (count > 0) 
Total runtime: 0.290 ms 

而且,这两个表定义... Products表第一:

=> \d products 
      Table "public.products" 
Column |   Type   | Modifiers 
--------+------------------------+----------- 
id  | integer    | not null 
title | character varying(100) | 
type | integer    | 
price | double precision  | 
filler | character(500)   | 
Indexes: 
    "products_pkey" PRIMARY KEY, btree (id) 
    "products_type_idx" btree (type) 
Referenced by: 
    TABLE "orderline" CONSTRAINT "orderline_p_id_fkey" FOREIGN KEY (p_id) REFERENCES products(id) 
    TABLE "stock" CONSTRAINT "stock_p_id_fkey" FOREIGN KEY (p_id) REFERENCES products(id) 

库存表:

=> \d stock 
    Table "public.stock" 
Column | Type | Modifiers 
--------+---------+----------- 
w_id | integer | not null 
p_id | integer | not null 
count | integer | 
Indexes: 
    "stock_pk" PRIMARY KEY, btree (w_id, p_id) 
    "stock_p_id_idx" btree (p_id) 
Foreign-key constraints: 
    "stock_p_id_fkey" FOREIGN KEY (p_id) REFERENCES products(id) 
    "stock_w_id_fkey" FOREIGN KEY (w_id) REFERENCES warehouses(id) 
+0

发布查询和解释计划请 – Samson 2012-04-18 11:04:45

+0

什么是您的PostgreSQL版本? – vyegorov 2012-04-19 08:02:13

回答

4

实际内部索引扫描的行是每次调用时返回的平均行数。在http://www.postgresql.org/docs/current/static/using-explain.html

展望:

在某些查询计划,有可能一个子规划节点被多次执行。例如,在上面的嵌套循环计划中,每个外部行执行一次内部索引扫描。在这种情况下,循环值报​​告节点的执行总次数,显示的实际时间和行值是每次执行的平均值。这样做的目的是使数字与显示成本估算的方式相当。乘以循环值以获得节点中实际花费的总时间。

我不知道它是如何四舍五入(我猜向下调整至最接近INT,平均之后),但它可能是在products大多数的行不具有相应的行stock

相关问题