我有一个名为的表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( 弧度( LATITUDE ) ) * cos( 弧度( Store.latitude ) ) * cos( 弧度( Store.longitude ) - 弧度( LONGITUDE ) ) + sin( 弧度) ( LATITUDE ) ) * sin( 弧度(Store.latitude ) ) )