我有一个查询,它使用嵌套循环将两个表TableA和TableB等价联接。由于存在“等价”联接约束,因此结果中返回的所有行将对应于这两个表中的至少一个行。但是,根据计划(EXPLAIN ANALYZE),即使在最终结果中返回了一行,实际从TableB开始的行计数也为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
还有两个表定义...产品表首先:
=> \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)
最佳答案
内部索引扫描的实际行是每次调用返回的平均行数。
看http://www.postgresql.org/docs/current/static/using-explain.html:
我不确定它是如何四舍五入的(我在平均后猜测是最接近的整数),但是可能是products
中的大多数行在stock
中没有相应的行。