【问题标题】:Mysql limit on left join resultsMysql对左连接结果的限制
【发布时间】: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 不行吗?
  • LIMIT results in MySQL?的可能重复
  • 感谢@MTK .. 但这只会限制整个位置查询。我们想限制左连接的结果匹配元素。添加到最后一条语句只是限制返回的位置数量,而不是每个位置的分支数量。我们想要所有位置以及每个位置 25 英里范围内的前 5 个(最大)。

标签: mysql geolocation


【解决方案1】:

好吧,在拉了很多头发之后,我终于找到了答案:

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 英里。

每个表(地址和分支)都有 lat、lng 和地理空间位置列。

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

希望这对某人有价值。

【讨论】:

    猜你喜欢
    • 2011-02-23
    • 2018-10-15
    • 2020-08-14
    • 2016-08-12
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多