Postgresql 本例为b
对于在外部表中找到的每一行,PostgreSQL都会扫描内部表(在本例中为Postgresql 本例为b,postgresql,sql-execution-plan,Postgresql,Sql Execution Plan,对于在外部表中找到的每一行,PostgreSQL都会扫描内部表(在本例中为a)以查找匹配的行 因为在内部表的连接条件上有一个索引,所以PostgreSQL在那里使用索引扫描 因此,对于嵌套循环联接,只能使用内部表上联接条件的索引 外部表的扫描也有一个条件(b.id
a
)以查找匹配的行
因为在内部表的连接条件上有一个索引,所以PostgreSQL在那里使用索引扫描
因此,对于嵌套循环联接,只能使用内部表上联接条件的索引
外部表的扫描也有一个条件(b.id<10000
),但这与连接无关。该列上似乎没有索引,因此使用了顺序扫描
扫描外部表时发现的19998行解释了内部循环的大量执行:对于这些行中的每一行,都会扫描内部表
几乎所有的执行时间都花在并行顺序扫描上,大多数行都被丢弃,因此我假设以下索引将使查询速度大大加快:
CREATE INDEX ON b (id);
Laurenz Albe,谢谢你的帮助。我已经按照你的指示,创建了一个索引,审查了执行计划,并补充了测试过程。Laurenz Albe,感谢你的帮助。我已经按照您的指示,创建了一个索引,审查了执行计划,并补充了测试过程。
music=# CREATE INDEX idx_b_id ON b(id);
WARNING: concurrent insert in progress within table "b"
CREATE INDEX
music=# set max_parallel_workers_per_gather = 6;
SET
music=# EXPLAIN (ANALYZE,VERBOSE) SELECT b.name FROM a,b WHERE a.id = b.id AND b.id < 10000;
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------
-------------------
Gather (cost=1388.64..108804.88 rows=20599 width=13) (actual time=1.316..35.770 rows=19998 loops=1)
Output: b.name
Workers Planned: 3
Workers Launched: 3
-> Nested Loop (cost=388.64..105744.98 rows=6645 width=13) (actual time=0.341..27.475 rows=5000 loops=4)
Output: b.name
Worker 0: actual time=0.095..26.337 rows=5365 loops=1
Worker 1: actual time=0.091..26.641 rows=5753 loops=1
Worker 2: actual time=0.101..28.578 rows=3145 loops=1
-> Parallel Bitmap Heap Scan on public.b (cost=388.08..51229.82 rows=6645 width=17) (actual time=0.298..1.265 rows=5000 loops=4)
Output: b.id, b.name
Recheck Cond: (b.id < 10000)
Heap Blocks: exact=31
Worker 0: actual time=0.044..1.111 rows=5365 loops=1
Worker 1: actual time=0.044..1.205 rows=5753 loops=1
Worker 2: actual time=0.049..0.681 rows=3145 loops=1
-> Bitmap Index Scan on idx_b_id (cost=0.00..382.93 rows=20599 width=0) (actual time=1.012..1.012 rows=19998 loops=1)
Index Cond: (b.id < 10000)
-> Index Only Scan using idx_para_select_id on public.a (cost=0.56..8.19 rows=1 width=4) (actual time=0.004..0.004 rows=1 loops=19998)
Output: a.id
Index Cond: (a.id = b.id)
Heap Fetches: 19998
Worker 0: actual time=0.004..0.004 rows=1 loops=5365
Worker 1: actual time=0.003..0.004 rows=1 loops=5753
Worker 2: actual time=0.004..0.004 rows=1 loops=3145
Planning Time: 0.264 ms
Execution Time: 37.025 ms
(27 rows)
CREATE INDEX ON b (id);