[英]Does group by with having require aggregate function on the select instruction?
[英]Select rows using GROUP BY and HAVING with aggregate function
我的桌子上摆满了公共汽车站。 每个站点都有line_id , 方向和坐标 (纬度和经度)。
我希望查询返回每条线/方向的最近停靠点。
SELECT * from stops GROUP BY CONCAT(line_id, direction)
该查询按预期将我的停靠站分组。 这是另一个比较棘手的部分(返回最近的停靠点),因为我正在使用来动态计算距离(我在这里替换了一些变量)
SQRT(POW(111.1819*(45.54182-lat),2)+POW(64.7938007101048*(-73.62934-lng),2))
我尝试做一个INNER JOIN,但是没有运气(我已经替换了距离公式):
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)
但是我一直在“ on子句”错误中得到一个未知列“ distance1” 。
我已经研究了其他选项,但是在查询中计算距离的事实似乎是一个真正的难题。 我有什么选择? 我需要我的查询尽可能快。
未经测试:
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子句中使用别名distance1,除非它在子查询中像第一个示例一样。
另外,为了加快计算速度,您无需取任何平方根,因为sqrt(x)<sqrt(y)表示x <y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.