Effectively selecting the closest (distance) record from a database

前端 未结 4 1852
再見小時候
再見小時候 2020-12-16 03:53

I\'ve got a database with a 40k venues and growing right now.

Assuming I\'m the red dot

\"Easy\"
I

4条回答
  •  生来不讨喜
    2020-12-16 04:38

    There is no effective way to find the distance except by trial and error. That is, using MySQL, you can't rank the records by distance from the target then select the top one. The best way is to pick a distance which you think the closest record will be within. Too big a number and you'll get too many records, too small a number and you won't get any. Lets say you pick 40 units.

    WHERE xcoord BETWEEN n - 40 AND n + 40 AND ycoord BETWEEN n - 40 AND n + 40
    

    Now you've got all the records with co-ordinates inside an 80 x 80 box, with your target as the centre (the box will be a bit skewed if you're working in latitude and longitude, but that doesn't really matter). Now use the Haversine equation if you're working with latitude and longitude, or Pythagoras if it's just Cartesian, to calculate the distance between the target and each of the points.

提交回复
热议问题