美文网首页
MySQL根据经纬度按距离排序

MySQL根据经纬度按距离排序

作者: yellow_han | 来源:发表于2019-01-20 19:46 被阅读0次

1、新建表

DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
  `id` int(11) unsigned NOT NULL auto_increment COMMENT '自增主键',
  `name` varchar(50) NOT NULL COMMENT '名称',
  `lon` double(9,6) NOT NULL COMMENT '经度',
  `lat` double(8,6) NOT NULL COMMENT '纬度',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='商户表';

2、插入数据

INSERT INTO `customer` VALUES ('1', '天津市区', '117.315575', '39.133462');
INSERT INTO `customer` VALUES ('2', '北京市区', '116.407999', '39.894073');
INSERT INTO `customer` VALUES ('3', '保定', '115.557124', '38.853490');
INSERT INTO `customer` VALUES ('4', '石家庄', '114.646458', '38.072369');
INSERT INTO `customer` VALUES ('5', '昌平区1', '116.367180', '40.009561');
INSERT INTO `customer` VALUES ('6', '海淀区2', '116.313425', '39.973078');
INSERT INTO `customer` VALUES ('7', '海淀区1', '116.329236', '39.987231');

3、计算方法

一:

SELECT
    *,
    ROUND(
        6378.138 * 2 * ASIN(
            SQRT(
                POW(
                    SIN(
                        (
                            40.0497810000 * PI() / 180 - lat * PI() / 180
                        ) / 2
                    ),
                    2
                ) + COS(40.0497810000 * PI() / 180) * COS(lat * PI() / 180) * POW(
                    SIN(
                        (
                            116.3424590000 * PI() / 180 - lon * PI() / 180
                        ) / 2
                    ),
                    2
                )
            )
        )
    ) AS juli
FROM
    customer
ORDER BY
    juli ASC

二:

st_distance 计算的结果单位是度,需要乘111195(地球半径6371000*PI/180)是将值转化为米。
SELECT
    *,
    (st_distance (point (lon,lat),point (116.3424590000,40.0497810000))*111195/1000 )as juli
FROM
    customer
ORDER BY
    juli ASC    

相关文章

网友评论

      本文标题:MySQL根据经纬度按距离排序

      本文链接:https://www.haomeiwen.com/subject/tekfjqtx.html