如何按给定点的距离对行进行排序,mysql?

Val*_*lev 5 mysql distance spatial geospatial

我试图从我的桌子获得100分,距离给定点的距离最小.

我正在使用

SELECT *, GLENGTH(
            LINESTRINGFROMWKB(
              LINESTRING(
                ASBINARY(
                  POINTFROMTEXT("POINT(40.4495 -79.988)")
                ),
                ASBINARY(pt)
              )
            )
          )
 AS `distance` FROM `ip_group_city` ORDER BY distance LIMIT 100
Run Code Online (Sandbox Code Playgroud)

(是的,这很痛苦.我只是用Google搜索它.我不知道如何正确测量MySQL中的距离)

执行需要很长时间.EXPLAIN说没有possible_keys.

我在列SPATIAL上创建了一个索引pt:

CREATE SPATIAL INDEX sp_index ON  ip_group_city (pt);
Run Code Online (Sandbox Code Playgroud)

虽然我真的不知道如何正确使用它.你能帮我么?

小智 6

因为您没有WHERE子句因此没有受影响的索引.我认为你应该通过使用MBR_(MySQL 5.0或更高版本)或ST_函数(MySQL 5.6或更高版本)添加来改进此查询.就像是:

SELECT *, GLENGTH(
            LINESTRINGFROMWKB(
              LINESTRING(
                ASBINARY(
                  POINTFROMTEXT("POINT(40.4495 -79.988)")
                ),
                ASBINARY(pt)
              )
            )
          )
 AS `distance` 
FROM `ip_group_city` 
WHERE
MBRWithin(
        pt, -- your point
        GeomFromText('Polygon( -- your line (in polygon format) from pt to target point 
                        (
                            #{bound.ne.lat} #{bound.ne.lng}, --North East Lat - North East Long
                            #{bound.ne.lat} #{bound.sw.lng}, --North East Lat - South West Long
                            #{bound.sw.lat} #{bound.sw.lng}, --
                            #{bound.sw.lat} #{bound.ne.lng},
                            #{bound.ne.lat} #{bound.ne.lng}
                        )
                    )')
      )
ORDER BY distance LIMIT 100
Run Code Online (Sandbox Code Playgroud)