计算距离(毕达哥拉斯)

时间:2014-05-31 12:35:38

标签: mysql sql distance

这里的SQL新词总数。我创建了两个SQL表,一个包含有关酒店的信息,另一个包含有关景点的信息。

SELECT hotels.*, attractions.*,  
    ((ACOS(SIN(hotels.Hotel_Lat * PI() / 180) * SIN(attractions.Attraction_Lat * PI() / 180) +  
        COS(hotels.Hotel_Long * PI() / 180) * COS(attractions.Attraction_Long * PI() / 180) *  
        COS((hotels.Hotel_Long - attractions.Attraction_Long) * PI() / 180)) *   
        180 / PI()) * 60 * 1.1515) as distance  
FROM hotels join attractions

此查询返回“空”'距离。有什么想法吗?如果这有所不同,我会有负值经度吗?

2 个答案:

答案 0 :(得分:0)

你无法像这样计算距离,因为它不考虑地球的曲率。

经过一段谷歌搜索后,你会得到以下链接:http://zcentric.com/2010/03/11/calculate-distance-in-mysql-with-latitude-and-longitude/并且有正确的SQL查询:

SELECT ((ACOS(SIN($lat * PI() / 180) * SIN(`lat` * PI() / 180) + COS($lat * PI() / 180) * COS(`lat` * PI() / 180) * COS(($lon – `lon`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance 
FROM `members` 
HAVING distance<=’10′ 
ORDER BY distance ASC

所以对你来说它看起来像这样:

SELECT h.*, a.*,
    ((ACOS(SIN(h.Hotel_Lat * PI() / 180) * SIN(a.Attractions_Lat * PI() / 180) +
        COS(h.Hotel_Long * PI() / 180) * COS(a.Attractions_Long * PI() / 180) *
        COS((h.Hotel_Long - a.Attractions_Long) * PI() / 180)) * 
        180 / PI()) * 60 * 1.1515) as distance
FROM hotel h join attractions a

答案 1 :(得分:0)

你为什么要让自己变得非常复杂?只需启用MySQL Geospatial extensionsuse ST_Distance即可解决您的问题:

SELECT hotels.*, a.*,  ST_Distance(ST_MakePoint(hotels.Hotel_Lon, hotels.Hotel_Lat),  ST_MakePoint(a.Attractions_Long, a.Attractions_Lat) as distance FROM hotels join attractions a;

请注意,mysql的St_Distance函数不利用索引,只处理极坐标。

希望它有所帮助,如果您还有其他问题,请发表评论。

相关问题