我有一张桌子叫place
:
id | name | coordinates (longitude, latitude)
1 | London | -0.12574, 51.50853
2 | Manchester | -2.25, 53.41667
3 | Glasgow | -4.25, 55.86667
该coordinates
列属于点数据类型。我使用以下方法将点插入place
表中:
st_geomfromtext('point($longitude $latitude)', 4326)
请注意,我已经使用了 SRID。
给定任何坐标,我想找到离它最近的地方(按升序排列)。我目前提出的解决方案(通过阅读 MySQL 文档)如下所示:
select
*,
st_distance_sphere(`place`.`coordinates`, st_geomfromtext('Point($longitude $latitude)', 4326)) as distance
from place
order by distance asc;
在查看了这里和其他地方的无数类似问题之后,很明显这是一种鲜为人知(和更新的方式)的做事方式,因此没有太多内容,因此我正在寻找一些澄清。
我的问题是:
- 这是最好的解决方案/我这样做对吗?
- 这种方法会利用我在
coordinates
列上的空间索引吗? - 使用st_distance_sphere时,是否需要指定地球的半径才能获得准确的结果?(编辑:不,它默认使用地球的半径)
编辑,以下是这些答案:
explain select ...;
返回:
id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra
1 | SIMPLE | place | NULL | ALL | NULL | NULL | NULL | NULL | 115687 | 100.00 | Using filesort
flush status; select ...; show session status like 'Handler%';
返回:
Variable_name | Value
Handler_commit | 1
Handler_delete | 0
Handler_discover | 0
Handler_external_lock | 2
Handler_mrr_init | 0
Handler_prepare | 0
Handler_read_first | 1
Handler_read_key | 1001
Handler_read_last | 0
Handler_read_next | 0
Handler_read_prev | 0
Handler_read_rnd | 1000
Handler_read_rnd_next | 119395
Handler_rollback | 0
Handler_savepoint | 0
Handler_savepoint_rollback | 0
Handler_update | 0
Handler_write | 0