MySQL : 如何在 5.6.1 以上的 mysql 版本中从一个特殊点找到最近的多边形?

MySQL : how to find nearest polygon from a special point in mysql versions above 5.6.1?

我有一个 table urbanpolygons 包含多边形的列是 paths 我有一个被多边形包围的点,我想搜索多边形并找出哪个更近就我而言。

绿色方框(多边形)应该选哪一个!

我这样做是为了管理点是否在多边形内:

select * FROM urbanpolygons where ST_Contains(urbanpolygons.paths, GeomFromText('POINT(29.632262, 52.497868)'));

此问题与 Get polygons close to a lat,long in MySQL or MySQL Find Polygon Nearest to Point

不重复

我上面提到的那个老问题是 6 年前提出的,从那时起 mysql 中已经实现了大量地理空间功能。

考虑到 mysql < 5.6.1 产品的新功能,例如 ST_Contains 和 ...

,最好回答

sqlfiddle 不提供 MYSQL 5.6 以上的版本所以我决定在这里写一个小例子:

CREATE TABLE `urbanpolygons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) NOT NULL,
`paths` polygon NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id_UNIQUE` (`id`)
)
INSERT INTO urbanpolygons (`id`, `name`, `paths`) VALUES ('1', 'area_1', ST_GeomFromText('POLYGON ((29.63383 52.492869,29.63411 52.493942,29.634446 52.494586,29.634837 52.495658,29.635397 52.497289,29.635676 52.49804,29.635919 52.498856,29.636217 52.499778,29.63674 52.501345,29.636889 52.501967,29.637131 52.502847,29.636851 52.503405,29.636497 52.503748,29.635285 52.50495,29.634483 52.505808,29.632804 52.503641,29.631592 52.502053,29.629652 52.499628,29.628496 52.498126,29.629204 52.497783,29.629652 52.497482,29.630361 52.496774,29.631126 52.495594,29.632002 52.494242,29.632655 52.493577,29.633308 52.492912,29.63383 52.492869))'));
INSERT INTO urbanpolygons (`id`, `name`, `paths`) VALUES ('2', 'area_2', ST_GeomFromText('POLYGON ((29.633084 52.486968,29.632748 52.488384,29.629055 52.489929,29.625176 52.49023,29.625138 52.489328,29.624579 52.487869,29.624467 52.487311,29.627078 52.485809,29.628831 52.484179,29.630249 52.482634,29.631144 52.482419,29.633084 52.486968))'));
INSERT INTO urbanpolygons (`id`, `name`, `paths`) VALUES ('3', 'area_3', ST_GeomFromText('POLYGON ((29.622564 52.488553,29.624504 52.494046,29.626892 52.498853,29.630622 52.505204,29.632711 52.507436,29.628981 52.509153,29.624653 52.501085,29.620773 52.505376,29.616744 52.49645,29.617192 52.490956,29.622564 52.488553))'));

我有这个观点:

GeomFromText('POINT(29.630528, 52.492461)')

这个点在提供的多边形之外,但我想得到离这个点最近的多边形,这里是 area_1!

终于可以这样处理了:

幸运的是 ST_DISTANCE() 函数提供了我们从任何几何对象到其他对象的距离!(我相信点和多边形之间的距离是从点到最近的多边形边缘计算的,用 google 地图测试距离和提供的距离 ST_DISTANCE)

select id
    from (select st_distance(paths,POINT(29.630528, 52.492461))as polyDistance,id from urbanpolygons)as nearestPoly
    where polyDistance = (select MIN(st_distance(paths,POINT(29.630528, 52.492461))) from urbanpolygons);

我知道这有点复杂且效率低下,我很想学习任何更好的解决方案!