MySQL 空間位置座標 geometry 的使用

建表語句函數

CREATE TABLE `map` (
  `id` int(11) NOT NULL,
  `location` geometry NOT NULL,
  PRIMARY KEY (`id`),
  SPATIAL KEY `idx_location` (`location`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='空間位置信息';

插入數據code

INSERT INTO map (id, location) VALUES (1, ST_GeomFromText('POINT(121.366961 31.190049)'));

更新數據字符串

UPDATE map SET location = ST_GeomFromText('POINT(121.366961 31.190049)') where id = 1;

查詢數據io

SELECT id, ST_AsText(location) AS location FROM map;
ST_AsText()函數是將geometry類型轉化爲字符串

計算兩點距離map

// 計算結果單位是米,POINT()裏經緯度使用逗號分隔
SELECT ST_Distance_Sphere(POINT(121.590347, 31.388094), location) AS distance FROM map;

SELECT ST_Distance_Sphere((SELECT location FROM map WHERE id = 1), location) AS distance FROM map WHERE id = 2;

查詢指定距離範圍內的數據數據

SELECT 
id, 
ST_Distance_Sphere(POINT(121.590347, 31.388094), location) AS distance, 
ST_AsText(location) AS location 
FROM map 
WHERE distance < 1000 
ORDER BY distance ASC;
相關文章
相關標籤/搜索