建表和索引
CREATE TABLE `map` (
`id` int(11) NOT NULL,
`address` varchar(255) NOT NULL DEFAULT '',
`location` geometry NOT NULL,
PRIMARY KEY (`id`),
SPATIAL KEY `idx_location` (`location`)
)
插入数据
INSERT INTO map (id, address, location) VALUES (2, '南京', ST_GeomFromText('POINT(120.366961 30.190049)'));
简单搜索
SELECT address, ST_AsText(location) AS location FROM map;
搜索本地和数据库保存的位置距离
SELECT address, ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant FROM map;
搜索距离小于100000m城市,并按距离排序
SELECT id, address, ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant
FROM map
WHERE ST_Distance_Sphere(POINT(121.590347, 31.388094),location) < 100000 ORDER BY distant;