How to calculate distance between two points in MySQL
Sep 21, 2025 am 02:15 AMMySQL可通過Haversine公式或ST_Distance_Sphere函數(shù)計算地理距離,前者適用于所有版本,后者自5.7起提供更簡便準確的球面距離計算。
MySQL doesn't have a built-in function to calculate the exact geographic distance between two points on Earth by default, but you can compute it using latitude and longitude with mathematical formulas like the Haversine formula. This formula accounts for the curvature of the Earth and gives the great-circle distance between two points.
Using the Haversine Formula in MySQL
If you have a table with columns lat and lng (latitude and longitude), you can calculate the distance between two points (e.g., point A and point B) using this SQL expression:
<font face="Courier New">SELECT 6371 * ACOS( COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * COS(RADIANS(lng2) - RADIANS(lng1)) SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)) ) AS distance_km FROM your_table;</font>
Where:
- 6371 is the approximate radius of Earth in kilometers (use 3959 for miles).
- lat1, lng1: Latitude and longitude of the first point.
- lat2, lng2: Latitude and longitude of the second point.
- The result distance_km is in kilometers.
Example: Distance Between Two Specific Coordinates
To find the distance between New York City (40.7128, -74.0060) and Los Angeles (34.0522, -118.2437):
<font face="Courier New">SELECT 6371 * ACOS( COS(RADIANS(40.7128)) * COS(RADIANS(34.0522)) * COS(RADIANS(-118.2437) - RADIANS(-74.0060)) SIN(RADIANS(40.7128)) * SIN(RADIANS(34.0522)) ) AS distance_km;</font>
This returns approximately 3940 km.
Optimize with ST_Distance_Sphere (MySQL 5.7 )
Starting from MySQL 5.7, you can use the built-in ST_Distance_Sphere() function, which is simpler and more accurate:
<font face="Courier New">SELECT ST_Distance_Sphere( POINT(-74.0060, 40.7128), POINT(-118.2437, 34.0522) ) / 1000 AS distance_km;</font>
Note: POINT(longitude, latitude), not (lat, lng). The function returns distance in meters, so divide by 1000 for kilometers.
Using in a Query with a Table
If you want to find all locations within 50 km of a given point (e.g., 40.7128, -74.0060):
<font face="Courier New">SELECT *, ST_Distance_Sphere(POINT(-74.0060, 40.7128), POINT(lng, lat)) / 1000 AS distance_km FROM locations HAVING distance_km </font>
Basically, use ST_Distance_Sphere() if you're on MySQL 5.7 or later — it's cleaner and faster. Otherwise, go with the Haversine formula using trigonometric functions. Both methods work well for calculating distances between geographic points in MySQL.
The above is the detailed content of How to calculate distance between two points in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: MySQL's CASE statement is used to implement conditional logic in query, and supports two forms: simple and search. Different values ??can be dynamically returned in clauses such as SELECT, WHERE, and ORDERBY; for example, in SELECT, classification of scores by fractional segments, combining aggregate functions to count the number of states, or prioritizing specific roles in ORDERBY, it is necessary to always end with END and it is recommended to use ELSE to handle the default situation.

Create a shell script containing the database configuration and mysqldump command and save it as mysql_backup.sh; 2. Store MySQL credentials by creating ~/.my.cnf file and set 600 permissions to improve security, modify the script to use configuration file authentication; 3. Use chmod x to make the script executable and manually test whether the backup is successful; 4. Add timed tasks through crontab-e, such as 02/path/to/mysql_backup.sh>>/path/to/backup/backup.log2>&1, realize automatic backup and logging at 2 a.m. every day; 5.

INSERT...ONDUPLICATEKEYUPDATE implementation will be updated if it exists, otherwise it will be inserted, and it requires unique or primary key constraints; 2. Reinsert after deletion of REPLACEINTO, which may cause changes in the auto-increment ID; 3. INSERTIGNORE only inserts and does not repetitive data, and does not update. It is recommended to use the first implementation of upsert.

EXPLAINinMySQLrevealsqueryexecutionplans,showingindexusage,tablereadorder,androwfilteringtooptimizeperformance;useitbeforeSELECTtoanalyzesteps,checkkeycolumnsliketypeandrows,identifyinefficienciesinExtra,andcombinewithindexingstrategiesforfasterqueri

Use the DISTINCT keyword to remove duplicate values ??from the specified column and return unique values. 1. The basic syntax is SELECTDISTINCTcolumn_nameFROMtable_name; 2. Query the unique value of a single column, such as SELECTDISTINCTcityFROMcustomers; 3. Query the unique combination of multiple columns, such as SELECTDISTINCTcity, stateFROMcustomers; 4. Filter with the WHERE clause and get the unique value, such as SELECTDISTINCTproduct_nameFROMordersWHEREorder_date>'202

Subqueries can be used in WHERE, FROM, SELECT, and HAVING clauses to implement filtering or calculation based on the result of another query. Operators such as IN, ANY, ALL are commonly used in WHERE; alias are required as derivative tables in FROM; single values ??must be returned in SELECT; related subqueries rely on outer query to execute each row. For example, check employees whose average salary is higher than the department, or add the company average salary list. Subqueries improve logical clarity, but performance may be lower than JOIN, so you need to ensure that you return the expected results.

MySQL can calculate geographical distances through the Haversine formula or the ST_Distance_Sphere function. The former is suitable for all versions, and the latter provides easier and more accurate spherical distance calculations since 5.7.

Use UTC to store time, set the MySQL server time zone to UTC, use TIMESTAMP to realize automatic time zone conversion, adjust the time zone according to user needs in the session, display the local time through the CONVERT_TZ function, and ensure that the time zone table is loaded.
