php - 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`
但它不能正常工作
那么该怎么做呢?
解决方案
您不应该在 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
)
对于数字,您不应使用引号
推荐阅读
- reactjs - react-google-maps“'google'未定义”错误
- javascript - 为什么即使我没有明确使用 React,我也需要 import React 语句?
- apache-spark - 使用 PySpark 的 Librosa 特征提取方法
- python - 安装情节
- c++ - 在多个源文件中拆分代码,现在我收到一个数组错误
- android - 从 Firebase 只返回需要的值
- unity3d - Destroy(gameObject) 仅在订阅事件时有效
- javascript - 在 JavaScript 中预处理音频数据(fft 频谱、峰值等)
- react-native - 在按钮按下 React Native 时重置 StackNavigator
- html - 我怎样才能在这里使用另一个 css 库颜色而不是 Material Design?