【发布时间】:2018-02-14 16:52:22
【问题描述】:
我正在尝试查找可以为我们的客户 (company_id) 位置列表提供服务的附近分支机构。这两个表(客户“位置”和我们的“分支机构”)都有索引的 lat / lng 字段。此 MySQL 查询使用 hasrsine 公式工作,并返回每个位置 25 英里内的所有分支。
select locations.id,locations.street, locations.city, locations.state,branches.id, branchname,branches.city,branches.state,
(3956 * acos(cos(radians(locations.lat))
* cos(radians(branches.lat))
* cos(radians(branches.lng)
- radians(locations.lng))
+ sin(radians(locations.lat))
* sin(radians(branches.lat)))) as branchdistance
from locations
left join branches on
(3956 * acos(cos(radians(locations.lat))
* cos(radians(branches.lat))
* cos(radians(branches.lng)
- radians(locations.lng))
+ sin(radians(locations.lat))
* sin(radians(branches.lat)))) < 25
where locations.company_id = 388
order by locations.id, branchdistance
但是我想将返回的分支数(左连接)限制为最多 5 个。 任何帮助将不胜感激。 谢谢
【问题讨论】:
-
order by locations.id, branchdistance LIMIT 5不行吗? -
感谢@MTK .. 但这只会限制整个位置查询。我们想限制左连接的结果匹配元素。添加到最后一条语句只是限制返回的位置数量,而不是每个位置的分支数量。我们想要所有位置以及每个位置 25 英里范围内的前 5 个(最大)。
标签: mysql geolocation