MySQL calculates the distance between coordinate fields and sorts based on that distance.

In MySQL, you can use spatial functions to calculate the distance between coordinate fields and sort based on this distance.

First, make sure spatial functions are enabled in MySQL. This can be checked with the following command:

SHOW VARIABLES LIKE 'version_compile_machine';

If the result contains "WITH_SPATIAL", spatial functions are enabled.

Let's say we have a table called "locations" that contains a coordinate field called "coordinates" (using point type). We can use the following SQL query to sort based on the distance of the coordinate field:

SELECT *
FROM locations
ORDER BY ST_Distance(coordinates, POINT(目标经度, 目标纬度));
  1. Replace "locations" with the actual table name.
  2. Replace "coordinates" with the actual coordinates field name.
  3. Replace "Target Longitude" and "Target Latitude" with the actual longitude and latitude values ​​of your target location.

This SQL query will return all records sorted by distance. More recent records will be ranked first.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/134680840