表结构及数据
DROP TABLE IF EXISTS `tb_locationpoint`;
CREATE TABLE `tb_locationpoint`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`province` varchar(20) NOT NULL COMMENT '省份',
`city` varchar(20) NOT NULL COMMENT '城市',
`longitude` double(10, 3) NOT NULL COMMENT '经度',
`latitude` double(10, 3) NOT NULL COMMENT '纬度',
PRIMARY KEY (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
INSERT INTO `tb_locationpoint`
VALUES (1, '山东', '济南', 116.938477, 36.597889),
(2, '河北', '石家庄', 114.477539, 38.030786),
(3, '浙江', '杭州', 120.058594, 30.334954),
(4, '河南', '郑州', 113.629, 34.744),
(5, '安徽省', '合肥', 117.170, 31.520);
查询
SELECT id, province, city,
round((st_distance(
point(longitude, latitude),
point(116.28, 39.54)
) / 0.0111) * 1000)AS distance
FROM `tb_locationpoint`
ORDER BY distance;
round函数
用于数据的四舍五入,它有两种形式:
round(x,d)
,x指要处理的数,d是指保留几位小数
这里有个值得注意的地方是,d可以是负数,这时是指定小数点左边的d位整数位为0,同时小数位均为0;round(x)
,其实就是round(x,0),也就是默认d为0;
st_distance
为mysql5.6+版本中开始自带的经纬度计算函数
point
在MySQL中的point用于表示GIS中的地理坐标