重构使用PostGIS函数的SQL查询

时间:2016-06-27 18:43:59

标签: sql postgresql

我有一个如下所示的查询:

 SELECT *,
        ST_Distance(
          ST_GeographyFromText('SRID=4326;POINT(' || users.longitude || ' ' || users.latitude || ')'),
          ST_GeographyFromText('SRID=4326;POINT(-84.334078 45.273343)')) as distance
        FROM users
        WHERE ST_DWithin(
          ST_GeographyFromText('SRID=4326;POINT(' || users.longitude || ' ' || users.latitude || ')'),
          ST_GeographyFromText('SRID=4326;POINT(-84.334078 45.273343)'),
          2000
        )
        ORDER BY distance ASC;"

我在这里看到了一些重复。我想知道有没有办法让这个查询更具可读性?

1 个答案:

答案 0 :(得分:1)

横向加入:

select *, ST_Distance(a, b) distance
from
    users,
    ST_GeographyFromText('SRID=4326;POINT(' || users.longitude || ' ' || users.latitude || ')') a,
    ST_GeographyFromText('SRID=4326;POINT(-84.334078 45.273343)') b
where ST_DWithin(a, b, 2000)
order by distance asc;