首页 > 解决方案 > mysql如何以最近的距离加入

问题描述

我正在使用 MySQL 和 PHP,我有一个商店表和商店分支表,我需要获取最近的分支名称和 id 的商店

1 - 商店

|---------------------|------------------| 
|         id          |     name         |
|---------------------|------------------|
|          1          |     store1       |
|---------------------|------------------|
|          2          |    store 2       |
------------------------------------------

2- store_branches

    |---------------------|------------|------------------| --------------|-------------|
    |         id          |  store_id  |     name         |   lat         |   lng       |
    |---------------------|------------|------------------|---------------|-------------|
    |          1          |      1     |     branch x     |   30.134166   |  31.384267  |
    |---------------------|------------|------------------|---------------|-------------|
    |          2          |      1     |     branch y     |   31.134168   |  32.384267  |
    |---------------------|------------|------------------|---------------|-------------|
    |          3          |      2     |     branch v     |   34.134140   |  36.384267  |
    |---------------------|------------|------------------|---------------|-------------|
    |          1          |      2     |     branch f     |   36.134181   |  31.384267  |
    |---------------------|------------|------------------| --------------|-------------|

我需要做的是从用户那里获取带有 nears 分支的商店列表

假设用户 lat = 30.0736176 & lng = 31.3418702

听到我是如何尝试做到的

select `store_branches`.`id` as `branch_id`, `stores`.`id` as `store_id`, `stores`.`name` as `store_name`  
from `stores` 
inner join `store_branches` on stores.id = (
                        SELECT `id` 
                        from `store_branches` 
                        WHERE store_branches.store_id = stores.id
                        order by POW(69.1 * (store_branches.lat - '30.0736176' ), 2) +
                        POW(69.1 * ( '31.3418702' - store_branches.lng) * COS(store_branches.lat / 57.3), 2) asc 
                        limit 1
                     )
 group by `stores`.`id`

但它不能正常工作

那么该怎么做呢?

标签: phpmysqlgoogle-maps

解决方案


您不应该在 mysql 版本 > 5.6 中使用没有聚合功能的 group by

    Select DISTINCT `store_branches`.`id` as `branch_id`, `stores`.`id` as `store_id`, `stores`.`name` as `store_name`  
    from `stores` 
    inner join `store_branches` on stores.id = (
                            SELECT `id` 
                            from `store_branches` 
                            WHERE store_branches.store_id = stores.id
                            order by (POW(69.1 * (store_branches.lat - 30.0736176 ), 2) +
                            POW(69.1 * ( 31.3418702 - store_branches.lng) * COS(store_branches.lat / 57.3), 2)) asc 
                            limit 1
                         )

对于数字,您不应使用引号


推荐阅读