SELECT city, (6372.797 * acos(cos(radians({$latitude})) * cos(radians(`latitude_range`)) * cos(radians(`longitude_range`) - radians({$longitude})) + sin(radians({$latitude})) * sin(radians(`latitude_range`)))) AS distance FROM cities WHERE active = 1 HAVING distance > 25 ORDER BY distance ASC
我希望能够抓住距离大于25公里且小于50公里的所有城市HAVING
。我尝试输入的任何内容都会导致所有城市超过25KM或出错。
如何将HAVING distance > 25 AND distance <= 50
添加到我的SQL查询中?
答案 0 :(得分:7)
正是你在问题中的方式:
SELECT city, (6372.797 * acos(cos(radians({$latitude})) * cos(radians(`latitude_range`)) * cos(radians(`longitude_range`) - radians({$longitude})) + sin(radians({$latitude})) * sin(radians(`latitude_range`)))) AS distance
FROM cities
WHERE active = 1
HAVING distance > 25 and distance <= 50
ORDER BY distance ASC;
就像一个小注释:使用having
子句来过滤列别名(如distance
)是一个MySQL扩展。在大多数数据库中,您必须使用子查询。