找到MYSQL中两点之间的距离。 (使用Point数据类型)

时间:2010-02-16 01:53:59

标签: mysql database indexing point

假设我有一个像这样的2列表:

| user_id      | int(11) | NO   | UNI | NULL    |                |
| utm          | point   | NO   | MUL | NULL    |                |

如您所见,它非常简单。 utm是 Point 数据类型。我这样插入:

INSERT INTO mytable(user_id, utm) VALUES(1, PointFromWKB(point(50, 50)));

然后,我创建一个空间索引。

ALTER TABLE mytable ...add spatial index on(utm) or something. (forgot)

好吧,一切都很好。现在,我想选择*距离< 99999 但它不起作用!

//This is supposed to select all where the distance is less than 99999999.
set @mypoint = PointFromWKB(point(20,20))
select * from mytable where GLength(LineString(utm, @mypoint)) < 9999999;
Empty set (0.00 sec)
select * from mytable where GLength(LineStringFromWKB(LineString(utm, @mypoint))) < 9999;
Empty set (0.00 sec)

顺便说一句,我试图在没有PointFromWKB的情况下INSERT INTO ......它没有用......这就是为什么有人向我建议PointFromWKB。

4 个答案:

答案 0 :(得分:3)

解决。这就是我所做的:

where GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(@mypoint)))) < 9999999999999;

答案 1 :(得分:1)

您也可以这样做。不确定它是否更快。

select * from mytable where glength(geomfromtext(concat('linestring(', x(utm), ' ', y(utm), ',20 20', ')'))) < 99999999

答案 2 :(得分:0)

据我所知,你必须这样做 -

select * from mytable
   where 
    (
        GLength(
          LineStringFromWKB(
            LineString(
              geoPoint, 
              GeomFromText('POINT(51.5177 -0.0968)')
            )
          )
        )
      ) < 99999999

更多 this answer

答案 3 :(得分:0)

如果您将点视为地球上的经度和纬度值,您可以使用 ST_Distance_Sphere 函数计算两点之间的距离。

mysql> SET @p1 = ST_GeomFromText('POINT(3.13 52.5)');
Query OK, 0 rows affected (0.00 sec)

mysql> SET @p2 = ST_GeomFromText('POINT(100.4 27.8)');
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> SELECT  ST_Distance_Sphere(@p1, @p2) AS distance;
+-------------------+
| distance          |
+-------------------+
| 8053869.706740822 |
+-------------------+
1 row in set (0.05 sec)

您获得的价值来自米。您还可以将首选半径作为可选参数提供给函数 ST_Distance_Sphere 以计算距离。

您可以从官方文档中找到更多详细信息。 https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html