使用point类型来存储经纬度
CREATE TABLE locations ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), coordinates POINT );插入经纬度数据:
INSERT INTO locations (name, coordinates) VALUES
('Location A', POINT(40.7128, -74.0060)),
('Location B', POINT(34.0522, -118.2437)),
('Location C', POINT(51.5074, -0.1278));创建索引CREATE SPATIAL INDEX sp_index ON locations(coordinates);查询一公里内的数据
-- 假设指定的经纬度是 (40.7128, -74.0060)(纽约市中心)
SET @center_lat = 40.7128;
SET @center_lng = -74.0060;
SET @radius_km = 1;
SELECT
id,
name,
ST_X(coordinates) AS latitude,
ST_Y(coordinates) AS longitude,
ST_DISTANCE(coordinates, POINT(@center_lat, @center_lng)) AS distance
FROM
locations
WHERE
ST_DISTANCE(coordinates, POINT(@center_lat, @center_lng)) <= @radius_km * 1000;
网友回复


