我正在使用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 分支的商店列表
假设用户纬度 = 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 为其他人引发错误 versuib 产生不可预测的结果...... 如果不想重复结果,请使用不同
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
)
对于数字,您不应使用引号