我正在尝试提高以下查询的性能。无论我如何编写查询(FROM子句中的子查询,WHERE子句中的子查询),postgres都坚持通过昂贵的ST_DWITHIN函数运行所有〜570K行,即使County = 24的行只有60行。在运行postgis函数之前,如何才能使postgres在County = 24上进行过滤,这对我来说似乎更快,更高效?700ms并不是引起太多关注的原因,但是随着该表增长到10M +,我开始关注性能。
还要注意,p.id是主键,p.zipcode是fk索引,z.county是fk索引,p.geom具有GiST索引。
查询:
EXPLAIN ANALYZE
SELECT count(p.id)
FROM point AS p
LEFT JOIN zipcode AS z
ON p.zipcode = z.zipcode
WHERE z.county = 24
AND ST_DWithin(
p.geom,
ST_SetSRID(ST_Point(-121.479756008715,38.563236291512),4269),
16090.0,
false
)
说明分析:
Aggregate (cost=250851.91..250851.92 rows=1 width=4) (actual time=724.007..724.007 rows=1 loops=1)
-> Hash Join (cost=152.05..250851.34 rows=228 width=4) (actual time=0.359..723.996 rows=51 loops=1)
Hash Cond: ((p.zipcode)::text = (z.zipcode)::text)
-> Seq Scan on point p (cost=0.00..250669.12 rows=7437 width=10) (actual time=0.258..723.867 rows=63 loops=1)
Filter: (((geom)::geography && '0101000020AD10000063DF8B52B45E5EC070FB752018484340'::geography) AND ('0101000020AD10000063DF8B52B45E5EC070FB752018484340'::geography && _st_expand((geom)::geography, 16090::double precision)) AND _st_dwithin((g (...)
Rows Removed by Filter: 557731
-> Hash (cost=151.38..151.38 rows=54 width=6) (actual time=0.095..0.095 rows=54 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 3kB
-> Bitmap Heap Scan on zipcode z (cost=4.70..151.38 rows=54 width=6) (actual time=0.023..0.079 rows=54 loops=1)
Recheck Cond: (county = 24)
Heap Blocks: exact=39
-> Bitmap Index Scan on fki_zipcode_county_foreign_key (cost=0.00..4.68 rows=54 width=0) (actual time=0.016..0.016 rows=54 loops=1)
Index Cond: (county = 24)
Planning time: 0.504 ms
Execution time: 724.064 ms
point
County = 24的〜60行全部复制到新表中时,查询只需要0.453毫秒(相比724毫秒),因此肯定有很大的不同。
count(*)
用作样式问题。id
如您所说,如果是pkid,则NOT NULL
表示它们相同。除了count(id)
具有您必须询问该问题是否id
可为空的缺点。