mysql 搜寻附近N公里内数据的实例

根据圆周率和地球半径系数以及搜寻点的经纬度,搜寻数据表中与搜寻点之间的距离为N公里内的数据。

1.创建测试表

CREATE TABLE `location` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `longitude` decimal(13,10) NOT NULL, `latitude` decimal(13,10) NOT NULL, PRIMARY KEY (`id`), KEY `long_lat_index` (`longitude`,`latitude`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.插入测试数据

insert into location(name,longitude,latitude) values ('广州东站',113.332264,23.156206), ('林和西',113.330611,23.147234), ('天平架',113.328095,23.165376);mysql> select * from `location`; +----+--------------+----------------+---------------+| id | name         | longitude      | latitude      | +----+--------------+----------------+---------------+|  1 | 广州东站      | 113.3322640000 | 23.1562060000 | |  2 | 林和西        | 113.3306110000 | 23.1472340000 ||  3 | 天平架        | 113.3280950000 | 23.1653760000 | +----+--------------+----------------+---------------+

3.搜寻1公里内的数据

搜寻点坐标:时代广场 113.323568, 23.146436

6370.996公里为地球的半径

计算球面两点坐标距离公式

C = sin(MLatA)sin(MLatB)cos(MLonA-MLonB) + cos(MLatA)cos(MLatB)
 Distance = RArccos(C)*Pi180

根据计算公式得到查询语句如下:

select * from `location` where ( acos(sin(([#latitude#]*3.1415)/180) * sin((latitude*3.1415)/180) + cos(([#latitude#]*3.1415)/180) * cos((latitude*3.1415)/180) * cos(([#longitude#]*3.1415)/180 - (longitude*3.1415)/180))*6370.996)<p style="text-align: left;"><strong>执行查询:</strong></p><pre class="brush:php;toolbar:false;">mysql&gt; select * from `location` where (    -&gt; acos(    -&gt; sin((23.146436*3.1415)/180) * sin((latitude*3.1415)/180) +     -&gt; cos((23.146436*3.1415)/180) * cos((latitude*3.1415)/180) * cos((113.323568*3.1415)/180 - (longitude*3.1415)/180)    -&gt; )*6370.996    -&gt; )<p style="text-align: left;">本文讲解了<a style="color:#f60; text-decoration:underline;" title="mysql" href="https://www.php.cn/zt/15713.html" target="_blank">mysql</a> 搜寻附近N公里内数据的实例相关内容,更多相关知识请关注php中文网。<br></p><p style="text-align: left;">相关推荐:<br><a href="http://www.php.cn/php-weizijiaocheng-402168.html" target="_blank">mysql 连接闪断自动重连的方法</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/php-weizijiaocheng-402168.html" target="_blank">mysql 连接闪断自动重连的方法</a><br></p><p style="text-align: left;"><a href="http://www.php.cn/php-weizijiaocheng-402168.html" target="_blank">mysql 连接闪断自动重连的方法</a><br></p>

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享