Postgres地理位置点距离

时间:2013-11-18 06:31:07

标签: sql postgresql

我正在尝试查询以确定Postgres数据库中地理位置点之间的距离这是我的查询

SELECT latitude, longitude, SQRT(
POW(69.1 * (latitude - 31.8679), 2) +
POW(69.1 * (-116.6567 - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM locations 
HAVING distance < 25 
ORDER BY distance

但它给了我这个错误

  

错误:列“距离”不存在   第5行:距离<1。 25

如果我删除部分“HAVING distance&lt; 25”,则查询运行正常

2 个答案:

答案 0 :(得分:4)

好的,我解决了其他问题

SELECT t.* FROM (
SELECT latitude, longitude,SQRT(POW(69.1 * (latitude - 31.8679), 2) +
POW(69.1 * (-116.6567 - longitude) * COS(latitude / 57.3), 2)) AS distance 
FROM Locations) t
WHERE distance < 1
ORDER BY distance 

答案 1 :(得分:4)

HAVING过滤器GROUP BY和聚合函数,而WHERE过滤行。 WHERE发生在SELECT之前,因此距离列无法在WHERE子句中进行过滤。

查询1可以写成

SELECT latitude, longitude, SQRT(
POW(69.1 * (latitude - 31.8679), 2) +
POW(69.1 * (-116.6567 - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM locations 
WHERE SQRT(
POW(69.1 * (latitude - 31.8679), 2) +
POW(69.1 * (-116.6567 - longitude) * COS(latitude / 57.3), 2)) < 25 
ORDER BY distance

使用子查询,内部查询在外部查询之前构建,因此 t.distance 可用于外部查询。