HashAggregate (cost=10.77..10.87 rows=10 width=12) (actual time=0.043..0.044 rows=10.00 loops=1) Group Key: user_id -> Index Scan using test_pkey on test (cost=0.29..10.27 rows=99 width=8) (actual rows=99.00 loops=1)
loops > 1 时 actual time 与 rows 都是每次循环的平均值:总耗时约 actual time * loops,总行数是 rows * loops,嵌套循环的内侧节点最容易踩这个坑。
关键节点
扫描节点
1 2 3 4 5 6 7 8
Seq Scan on orders (cost=0.00..18334.00 rows=1000 width=45) Filter: (status = 'pending'::text) Rows Removed by Filter: 999000 Index Scan using idx_orders_user on orders (cost=0.42..8.45 rows=1 width=45) Index Cond: (user_id = 42) Index Only Scan using idx_orders_user_status on orders (cost=0.42..4.53 rows=1 width=8) Heap Fetches: 0 Bitmap Heap Scan on orders (cost=5.06..224.98 rows=100 width=45) Recheck Cond: (user_id < 100) -> Bitmap Index Scan on idx_orders_user
Seq Scan 顺序读整表,表小、或条件命中大部分行时是正确选择;大表上伴随很高的 Rows Removed by Filter 才是问题信号。
Index Scan 沿索引定位行位置再回表,取少量行时最优;取大量行时回表的随机读可能比顺序扫描更贵,优化器会因此改选 Seq Scan。
Index Only Scan 要求查询涉及的列都在索引里(PG 11 起可用 CREATE INDEX ... INCLUDE (...) 追加非键列),但仍需确认行对当前快照可见——可见性记录在堆页的 visibility map、由 VACUUM 维护;Heap Fetches 很高说明多数行还是回了表,覆盖索引没达到预期。
Bitmap Index Scan 收集行位置、Bitmap Heap Scan 按物理顺序批量回表,适合命中行数中等、条件可组合(BitmapAnd / BitmapOr)的场景;出现 Rows Removed by Index Recheck 说明位图退化为有损(lossy),回表后要重新检查条件。
连接节点
1 2 3 4 5 6 7
Nested Loop (cost=0.29..118.50 rows=10 width=488) -> Index Scan using idx_a on a (...) -> Index Scan using idx_b on b (loops=10) -- 内侧每轮执行一次 Hash Join (cost=226.23..709.73 rows=100 width=488) Hash Cond: (t2.user_id = t1.user_id) -> Hash (cost=224.98..224.98 rows=100 width=244) Batches: 1 Memory Usage: 35kB Merge Join (cost=0.56..233.49 rows=10 width=488) Merge Cond: (t1.id = t2.id)