SELECT *, ST_DISTANCE(geo_location, POINT(lon, lat)) AS distance
FROM geotable
ORDER by distance DESC
LIMIT 200;
壞消息是它會很慢,因爲st_distance()沒有使用空間索引。你應該嘗試用最大半徑來選擇較少的記錄來限制查詢:
set @dist = 100;
set @rlon1 = [email protected]/abs(cos(radians(lat))*69);
set @rlon2 = [email protected]/abs(cos(radians(lat))*69);
set @rlat1 = lat-(@dist/69);
set @rlat2 = lat+(@dist/69);
SELECT *, ST_DISTANCE(geo_location, POINT(lon, lat)) AS distance
FROM geotable
WHERE ST_WITHIN(geo_location,ENVELOPE(LINESTRING(point(@rlon1, @rlat1), point(@rlon2, @rlat2))))
ORDER by distance DESC
LIMIT 200;
或者,如果你有每個國家的多邊形座標,你可以用這個來代替最大半徑。
對不起,地理位置列上有一個空間索引。也試圖避免haversine。它似乎超級慢。 – stormchaser
我的意思是:即使它在InnodB中定義,ST_DISTANCE()也不使用空間索引。你必須在MYISAM中使用空間索引。 – Nikos