2016-10-04 97 views
-1

我想要做的是獲取最近的經緯度城市。
我的城市表有3個字段:緯度,經度,半徑:
我的查詢看起來是這樣的:Mysql order by別名

SELECT * 
FROM cities 
where st_distance_sphere(point(@lat, @lng), point(lat, lng)) <= area LIMIT 1 

我的問題是,我想距離進行排序。 (st_distance_sphere(point(@lat, @lng), point(lat, lng)))給出了距離。
但顯然我不能只是別名st_distance_sphere(point(@lat, @lng), point(lat, lng)) as distance並指定ORDER BY distance

那麼我如何根據距離排序結果呢?

回答

0

我希望查詢看起來像這樣:

SELECT c.*, 
     st_distance_sphere(point(@lat, @lng), point(lat, lng)) as dist 
FROM cities c 
HAVING st_distance_sphere(point(@lat, @lng), point(lat, lng)) <= area 
ORDER BY dist 
LIMIT 1 

這將使用MySQL擴展,允許HAVING子句中的條件,即使沒有GROUP BYHAVING子句允許您爲條件使用列別名,而不必使用子查詢。

0

嘗試使用

select b.* from (
SELECT a.*, st_distance_sphere(point(@lat, @lng), point(a.lat, a.lng)) as distance FROM cities a) b where b.distance<= area order by b.distance limit 1