选择附近有城市的城镇

时间:2015-07-08 10:46:30

标签: mysql distance

我有2个表格,如下面的示例,townsthings,并且需要获取距离该城镇记录x距离附近的城镇附近的城镇列表。纬度和经度将用于进行距离计算。

我已经查看了其他一些问题,并设法从things获取单个指定城镇的记录,但无法想到如何获取附近things所有城镇的列表离它们的距离比x更近。

能够根据x距离内附近物品的数量对结果城镇进行排序将是一个奖励。

TOWNS
+--------+----------+---------+---------+
| townId | townName | townLat | townLng |
+--------+----------+---------+---------+
|      1 | town a   |     1.5 |     1.9 |
|      2 | town b   |     1.4 |     3.8 |
|      3 | town c   |     2.3 |     2.7 |
|      4 | town d   |     3.2 |     1.6 |
|    ... | ...      |     ... |     ... |
+--------+----------+---------+---------+

THINGS
+---------+-----------+----------+----------+
| thingId | thingName | thingLat | thingLng |
+---------+-----------+----------+----------+
|       1 | thing a   | 2.1      | 3.1      |
|       2 | thing b   | 1.1      | 2.3      |
|       3 | thing c   | 3.2      | 0.2      |
|       4 | thing d   | 1.3      | 1.1      |
|     ... | ...       | ...      | ...      |
+---------+-----------+----------+----------+

提前致谢

1 个答案:

答案 0 :(得分:2)

您可以CROSS JOIN获取城镇和事物的所有可能组合,然后计算每个城镇和物体之间的Haversine距离。我使用SELECT DISTINCT来确保城镇只在结果集中列出一次。

SELECT DISTINCT TOWNS.townName FROM
TOWNS CROSS JOIN THINGS
WHERE 3959 * acos( 
  cos(radians( TOWNS.townLat ))
* cos(radians( THINGS.thingLat ))
* cos(radians( TOWNS.townLng ) - radians( THINGS.thingLng ))
+ sin(radians( TOWNS.townLat )) 
* sin(radians( THINGS.thingLat ))
) < x

我使用的公式为英里x(地球的平均半径为3959英里)。