如何在PostgreSQL的地理数据上改进"GROUP BY"的"MAX"?

Iva*_*dev 7 sql postgresql

我有3列公司的地址表:company_id,lat,lon.

我需要与每家公司保持最近的距离.我为PostgreSQL 使用cubeearthdistance扩展.

查询工作正常但很慢:

SELECT
 company_id,
 MIN(earth_distance(ll_to_earth(lat,lon), ll_to_earth(53.96,83.96))) AS distance
FROM companies
GROUP BY company_id;
Run Code Online (Sandbox Code Playgroud)

GIST索引如:

CREATE INDEX i_name on companies USING gist(ll_to_earth(lat, lon));
Run Code Online (Sandbox Code Playgroud)

不使用.

我该如何解决这个问题?谢谢.

cle*_*ens 3

一般来说,索引可以帮助您从大表中查找几行或提高查询速度ORDER BY。您的查询需要扫描表中的所有行,并且它对所有行进行复杂的计算。因此,索引无法帮助您,因为 Postgres 不使用索引作为预先计算的值。

您应该将 的值预先计算ll_to_earth(lat, lon)到一个单独的列中,并在查询中使用该列。