我有一个名为stores
的表,其中包含商店信息,更重要的是包含各商家商店的位置坐标。商家可以在不同位置拥有多个商店。我需要按距离(从特定位置)订购的商店列表,其中只有每个商家中最近的商店显示在列表中。
以下查询有效,但我认为其次优。有没有办法修改或改进此查询?
SELECT
`Store`.`id`,
`Merchants`.`id`,
`Store`.`area_id`,
`Store`.`url`,
( 6371 * acos( cos( radians(18.973212066666665) ) * cos( radians( Store.latitude ) ) * cos( radians( Store.longitude ) - radians(72.8140959) ) + sin( radians(18.973212066666665) ) * sin( radians( Store.latitude ) ) ) ) AS distance
FROM
`stores` AS `Store`
INNER JOIN
(SELECT DISTINCT id,( 6371 * acos( cos( radians(18.973212066666665) ) * cos( radians( Store.latitude ) ) * cos( radians( Store.longitude ) - radians(72.8140959) ) + sin( radians(18.973212066666665) ) * sin( radians( Store.latitude ) ) ) ) AS distance FROM stores as Store WHERE Store.active=1 AND Store.parent_id=0 AND (( 6371 * acos( cos( radians(18.973212066666665) ) * cos( radians( Store.latitude ) ) * cos( radians( Store.longitude ) - radians(72.8140959) ) + sin( radians(18.973212066666665) ) * sin( radians( Store.latitude ) ) ) ) < 50) GROUP BY Store.id ORDER BY distance) AS `St` ON (`St`.`id` = `Store`.`id`)
INNER JOIN
merchants AS `Merchants` ON (`Store`.`merchant_id` = `Merchants`.`id`)
WHERE
(( 6371 * acos( cos( radians(18.973212066666665) ) * cos( radians( `Store`.`latitude` ) ) * cos( radians( `Store`.`longitude` ) - radians(72.8140959) ) + sin( radians(18.973212066666665) ) * sin( radians( `Store`.`latitude` ) ) ) ) < 50) AND
`Store`.`parent_id` = 0 AND
`Store`.`active` = 1
GROUP BY
`Merchants`.`id`
ORDER BY
`distance` ASC
LIMIT 10
我使用以下公式计算距离(6371 * acos(cos(弧度(纬度))* cos(弧度(Store.latitude))* cos(弧度(Store.longitude)) - 弧度( LONGITUDE ))+ sin(弧度( LATITUDE ))* sin(弧度(Store.latitude))))
答案 0 :(得分:0)
如果我理解您的需要,可以尝试此查询:
select id, merchant_id, area_id, url,
min(distance function you are using) as distance
from stores group by merchant id, order by distance
我实际上没有运行它,但这个想法应该有用。
-Mansi