我的(简化)查询:
SELECT a.id FROM a LEFT JOIN b ON b.id = a.id WHERE b.id IS NULL ORDER BY id;
像这样的查询计划有效:
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
Merge Anti Join (cost=0.57..3831.88 rows=128092 width=8)
Merge Cond: (a.id = b.id)
-> Index Only Scan using a_pkey on a (cost=0.42..3399.70 rows=130352 width=8)
-> Index Only Scan using b_pkey on b (cost=0.15..78.06 rows=2260 width=8)
(4 rows)
但是,如果计划者认为它可能会更好,有时 postgresql 9.5.9 会切换到顺序扫描(请参阅为什么 PostgreSQL 对索引列执行顺序扫描?)。然而,就我而言,这让事情变得更糟。
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
Merge Anti Join (cost=405448.22..39405858.08 rows=1365191502 width=8)
Merge Cond: (a.id = b.id)
-> Index Only Scan using a_pkey on a (cost=0.58..35528317.86 rows=1368180352 width=8)
-> Materialize (cost=405447.64..420391.89 rows=2988850 width=8)
-> Sort (cost=405447.64..412919.76 rows=2988850 width=8)
Sort Key: b.id
-> Seq Scan on b (cost=0.00..43113.50 rows=2988850 width=8)
(7 rows)
我的(hack)解决方案是通过以下方式阻止顺序扫描:
set enable_seqscan to off;
postgresql 文档说正确的方法是使用 ALTER TABLESPACE 对 seq_page_cost 进行处理。在索引列上使用 ORDER BY 时,这可能是可取的,但我不确定。https://www.postgresql.org/docs/9.1/static/runtime-config-query.html