MySQL对左连接结果的限制

标签 mysql geolocation

我正在尝试查找可以为我们的客户 (company_id) 位置列表提供服务的附近分支机构。这两个表(客户的“位置”和我们的“分支机构”)都有索引的纬度/经度字段。此 MySQL 查询使用半正矢公式进行工作,并返回每个位置 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 个。 任何帮助将不胜感激。 谢谢

最佳答案

经过一番绞尽脑汁,我终于找到了答案:

select 
a.id,
b.id,
st_distance_sphere(a.position, b.position)  * 0.00062137119 dist
from addresses a
inner join branches b
on b.id = (
    select b1.id
    from branches b1
    where st_distance_sphere(a.position, b1.position)  * 0.00062137119  < 25
    order by st_distance_sphere(a.position, b1.position) 
    limit 1
)

作为解释,我们试图将数千个线索(地址)分配给数百个分支机构中最近的一个,每个分支机构的服务半径为 25 英里。

每个表(地址和分支机构)都有纬度、经度和地理空间位置列。

我修改了原始查询以使用 MySQL 5.7 地理空间函数 (st_distance_sphere),但半正矢公式仍然有效。

希望这对某人有值(value)。

关于MySQL对左连接结果的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48792360/

相关文章:

mysql - 无法使用 shell 脚本将数据从 .csv 文件加载到 mysql 数据库

php - 使用 PDO 获取上一行以创建链接

php - 选择具有模式匹配的记录

javascript - 等到条件成立?

javascript - 状态零结果谷歌地图地理编码器状态

MySQL:在包含 url 的字段中按主机名搜索

php - 代码和 SQL 查询中有什么错误?为什么网页上没有任何显示?

iphone - 计算新坐标 x 米和 y 距一个坐标的度数

google-maps - 地址的地理编码是如何完成的?

javascript - Android 上的手机唤醒后 HTML5 GPS 地理定位失败