Postgres地理位置点距离

6

我正在尝试在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

但是它给了我这个错误

错误:列“distance”不存在 第5行:HAVING distance < 25

如果我删除“HAVING distance < 25”部分,查询就可以正常运行。

2个回答

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 

4

HAVING过滤器是用于GROUP BY和聚合函数的,而WHERE过滤器是用于行的过滤。由于WHERESELECT之前执行,因此distance列无法在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可以在外部查询中使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接