ORDER BY 在尝试按升序获取距离时不起作用
ORDER BY not working while trying to get distance by ascending order
select * from `users`
where exists (
select *, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances
from `locations`
where `users`.`location_id` = `locations`.`id`
and (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) < 32.688888
ORDER BY `distances` DESC)
您需要将 ORDER BY
放在主查询中。子查询只是用来判断一行是否存在,顺序无关紧要。
但是 distances
不是主查询中的列,因此您无法使用您编写的查询对其进行排序。而不是使用 EXISTS
,您需要加入子查询。
SELECT u.*, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances
FROM users AS u
JOIN locations AS l ON `u`.`location_id` = `l`.`id`
HAVING distances < 32.688888
ORDER BY distances DESC
select * from `users`
where exists (
select *, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances
from `locations`
where `users`.`location_id` = `locations`.`id`
and (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) < 32.688888
ORDER BY `distances` DESC)
您需要将 ORDER BY
放在主查询中。子查询只是用来判断一行是否存在,顺序无关紧要。
但是 distances
不是主查询中的列,因此您无法使用您编写的查询对其进行排序。而不是使用 EXISTS
,您需要加入子查询。
SELECT u.*, (6371 * acos(cos(radians(22.559648)) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(88.415552)) + sin(radians(22.559648)) * sin(radians(`lat`)))) AS distances
FROM users AS u
JOIN locations AS l ON `u`.`location_id` = `l`.`id`
HAVING distances < 32.688888
ORDER BY distances DESC