MySQL Query for Finding Locations Within a Radius
Queries that search for locations within a specified radius are used when dealing with geospatial data. In this case, a query is needed to retrieve all rows within a 25-mile radius of a given latitude and longitude. However, the original query was not returning accurate results for all rows.
Improved Query
The improved query eliminates the incorrect results by using a more accurate formula to calculate the distance between rows:
SELECT `id`, ( 6371 * acos( cos( radians( :lat ) ) * cos( radians( `lat` ) ) * cos( radians( `long` ) - radians( :long ) ) + sin(radians(:lat)) * sin(radians(`lat`)) ) ) `distance` FROM `location` HAVING `distance` < :distance ORDER BY `distance` LIMIT 25
Explanation
Parameters
Using this improved query, all rows within a specified radius can be accurately retrieved, eliminating the incorrect results seen in the original query.
The above is the detailed content of Here are a few title options, varying in style and focus: **Direct & Informative:** * **How to Find Locations Within a Radius Using MySQL: An Improved Query** * **Accurate Geolocation Search in. For more information, please follow other related articles on the PHP Chinese website!