明显需要位图堆扫描

问题描述 投票:0回答:1

我有这样的疑问:

SELECT 
  DISTINCT ON (services.group_id) 
  services.service_id,
  ...
FROM services
WHERE services.group_id IN ('67240181b97477f054f9b1bc', '67240181b97477f054f9b1be')

我有一个索引

group_id

为什么Postgres需要进行额外的堆扫描?我只想要任何匹配的

group_id
的第一场比赛。请注意,它应该具有来自
Bitmap Index Scan
的正确记录,该记录已经检查匹配
group_id

Unique  (cost=609.73..611.66 rows=50 width=240) (actual time=0.353..0.385 rows=2 loops=1)
  ->  Sort  (cost=609.73..610.70 rows=386 width=240) (actual time=0.353..0.364 rows=386 loops=1)
        Sort Key: group_id
        Sort Method: quicksort  Memory: 133kB
        ->  Bitmap Heap Scan on services  (cost=11.56..593.15 rows=386 width=240) (actual time=0.030..0.180 rows=386 loops=1)
              Recheck Cond: ((group_id)::text = ANY ('{67240181b97477f054f9b1bc,67240181b97477f054f9b1be}'::text[]))
              Heap Blocks: exact=39
              ->  Bitmap Index Scan on ix_services_group_id  (cost=0.00..11.46 rows=386 width=0) (actual time=0.019..0.020 rows=386 loops=1)
                    Index Cond: ((group_id)::text = ANY ('{67240181b97477f054f9b1bc,67240181b97477f054f9b1be}'::text[]))
Planning Time: 0.505 ms
Execution Time: 0.434 ms
postgresql
1个回答
0
投票

IN 子句的作用类似于 OR,这就是堆的原因

使用

SELECT 
  DISTINCT ON (services.group_id) 
  services.service_id,
  ...
FROM services
WHERE services.group_id = '67240181b97477f054f9b1bc'
UNION 
SELECT 
  DISTINCT ON (services.group_id) 
  services.service_id,
  ...
FROM services
WHERE services.group_id = '67240181b97477f054f9b1be'
© www.soinside.com 2019 - 2024. All rights reserved.