MySQL 空间位置坐标 geometry 的使用
Posted 小伍
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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=\'空间位置信息\';
插入数据
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;
查询数据
SELECT id, ST_AsText(location) AS location FROM map;
ST_AsText()函数是将geometry类型转化为字符串
计算两点距离
// 计算结果单位是米,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;
以上是关于MySQL 空间位置坐标 geometry 的使用的主要内容,如果未能解决你的问题,请参考以下文章