简体   繁体   中英

Find 5 closest points for all points in a MySQL table (Geo Spatial query)

I have a MySQL database table with 50,000 records, and I need to find the 5 closest points to each point to display on a website. Unfortunately, the query is computationally expensive, and takes a long time to query pretty much static information (the list of points will very rarely change)

I'm ultimately looking for a solution to crunch the entire table and set a new column with a list of the closest record IDs using something like GROUP_CONCAT to make a nice comma separated list

I can do one line at a time (Just using selects right now – updating rows after this is sorted)

SELECT c.ID, GROUP_CONCAT(items.ID) as list FROM cities as c, (SELECT ID FROM cities ORDER BY ST_Distance_Sphere(cord, POINT(-81.9242,32.5521), 3440) asc LIMIT 5) as items WHERE c.ID = 5185

cord is the lat/lng coordinate stored in the database as a geo-spacial POINT, The second ST_Distance_Sphere() Property is what is stored for the item ID 5185

Basically, I need to figure out how to either pass values into the nested SELECT query or there's a magic JOIN I'm not figuring out

I'm not aware of a magic JOIN in MySQL that would do it (PostgreSQL does have something close to such magic). What you can do lacking such magic is to use regular spatial join on distance condition.

The trick is that MySQL like many DBMS has spatial index support and reasonably fast spatial join when you use index and limit search using a distance condition. So if you query only points within a small distance - the query is much faster. The trick is how to figure out the appropriate distance? One way is to start with small search radius, then increase search radius for points where you did not find 5 points close enough.

I did couple posts about doing it in BigQuery, you can adapt the solution for MySQL and 5 nearest points rather than 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM