下面的传参是传入用户的经纬度 数据库的商家的经纬度字段为lat lng 以下sql我们就可以查询出距离小于5千米的前10个商家

SELECT
    a.*,
    (
    6371 * acos(
    cos( radians( a.lat ) ) * cos( radians( 31.8234360 ) ) * cos(
      radians( 117.2115230 ) - radians( a.lng )
  ) + sin( radians( a.lat ) ) * sin( radians( 31.8234360 ) )
    )
    ) AS distance
FROM
    merchant a
HAVING distance < 5
ORDER BY
    distance
    LIMIT 10

表结构和数据

CREATE TABLE `merchant`  (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` char(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
  `lat` double(11, 7) NOT NULL DEFAULT 0.0000000,
  `lng` double(11, 7) NOT NULL DEFAULT 0.0000000,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1004 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `merchant` VALUES (1, '合肥八中', 31.8149980, 117.2141820);
INSERT INTO `merchant` VALUES (2, '合肥西站', 31.8384680, 117.2229130);
INSERT INTO `merchant` VALUES (3, '天鹅湖万达', 31.8259520, 117.2277640);
INSERT INTO `merchant` VALUES (4, '新华学院', 31.8314740, 117.1909690);
INSERT INTO `merchant` VALUES (5, '1912', 31.8478850, 117.2276200);
INSERT INTO `merchant` VALUES (6, '和谐花园', 31.8427930, 117.2240990);
INSERT INTO `merchant` VALUES (7, '汇林阁', 31.8315660, 117.2256080);
INSERT INTO `merchant` VALUES (8, '兴园小区', 31.8234360, 117.2115230);
INSERT INTO `merchant` VALUES (9, '华地紫园', 31.8242330, 117.2059170);
INSERT INTO `merchant` VALUES (10, '合肥市政府', 31.8278230, 117.2336930);
INSERT INTO `merchant` VALUES (11, '银泰城', 31.8241410, 117.2393700);
INSERT INTO `merchant` VALUES (12, '蔚蓝商务', 31.8193240, 117.2402680);
INSERT INTO `merchant` VALUES (14, '天鹅湖万达', 31.8259520, 117.2277640);
最后修改:2020 年 05 月 16 日 01 : 51 PM
如果觉得我的文章对你有用,请随意赞赏