我有一张装满巴士站的桌子。每个停止都有一个 line_id ,a 方向坐标(lat和lng)。

我希望我的查询返回每个线/方向的最接近的停止。

SELECT * from stops GROUP BY CONCAT(line_id, direction)
.

查询按预期组的停止。这是另一部分的诡辩器(返回最接近的停止),因为我在使用时计算距离(我在此处替换一些变量)

SQRT(POW(111.1819*(45.54182-lat),2)+POW(64.7938007101048*(-73.62934-lng),2))
.

我试过做一个内心的一个,但没有运气(我已经更换了距离公式):

SELECT distance-formula as distance1, s1.* from stops s1 INNER JOIN 
(SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 
ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance1 = s2.distance2)
.

但我一直在错误上获取未知列'距离1'。

我已经研究了其他选项,但在查询中计算的距离似乎是一个真正的交易破坏者。我的选择是什么?我需要我的查询尽可能快。

有帮助吗?

解决方案

未经测试:

SELECT * FROM (SELECT distance-formula as distance1, line_id, direction from stops) s1 INNER JOIN (SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance1 = s2.distance2)
.

或(也未经测试):

SELECT distance-formula as distance1, s1.* from stops s1 INNER JOIN (SELECT MIN(distance-formula) AS distance2, line_id, direction FROM stops GROUP BY CONCAT(line_id, direction)) s2 ON (s1.line_id = s2.line_id AND s1.direction = s2.direction AND s1.distance - formula = s2.distance2)
.

您无法在Where或ON子句中使用别名距离1,除非它在像第一个示例中的子查询中。

也是为了加速计算的兴趣,您不需要拍摄任何内容,因为SQRT(x)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top