【问题标题】:MySQL 5.6 Find points within a distance and order by distance ASCMySQL 5.6 查找距离内的点并按距离排序 ASC
【发布时间】:2019-12-17 17:17:45
【问题描述】:

我有下表:

CREATE TABLE `places` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(256) DEFAULT NULL,
 `coordinates` point DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


INSERT INTO `places` ( `name`, `coordinates`)
VALUES ("Louvre ", POINT(48.861105, 2.335337));

INSERT INTO `places` ( `name`, `coordinates`)
VALUES ("Eiffel Tower", POINT(48.858271, 2.293795));

INSERT INTO `places` ( `name`, `coordinates`)
VALUES ("Pere Lachaise", POINT(48.861131, 2.394683));

INSERT INTO `places` ( `name`, `coordinates`)
VALUES ("Brooklyn", POINT(40.711089, -73.948391));

我想返回卢浮宫 5 英里范围内的所有地方,应该返回 3 条记录(卢浮宫、埃菲尔铁塔、拉雪兹佩尔)

我运行以下查询,但最终得到所有 4 条记录。我做错了什么?

 SET @radius = 5 * 1609.344; -- convert miles to meters

 SELECT name, ST_Distance(coordinates,POINT(48.861105, 2.335337)) AS distance 
   FROM places
  WHERE ST_Within(coordinates, ST_Buffer(POINT(48.861105, 2.335337),@radius))
ORDER BY distance ASC

注意:我知道 MySQL 5.7 有 ST_Distance_Sphere() 函数来实现上述功能,但我现在坚持使用 5.6。

任何帮助表示赞赏。

【问题讨论】:

    标签: geometry geospatial mysql-5.6


    【解决方案1】:

    您可以使用Haversine 公式填充ST_Distance_Sphere:

    DELIMITER $$
    
    CREATE FUNCTION `ST_Distance_Sphere` (point1 POINT, point2 POINT)
    
        RETURNS FLOAT
        no sql deterministic
        BEGIN
            declare R INTEGER DEFAULT 6371000;
            declare `φ1` float;
            declare `φ2` float;
            declare `Δφ` float;
            declare `Δλ` float;
            declare a float;
            declare c float;
            set `φ1` = radians(y(point1));
            set `φ2` = radians(y(point2));
            set `Δφ` = radians(y(point2) - y(point1));
            set `Δλ` = radians(x(point2) - x(point1));
    
            set a = sin(`Δφ` / 2) * sin(`Δφ` / 2) + cos(`φ1`) * cos(`φ2`) * sin(`Δλ` / 2) * sin(`Δλ` / 2);
            set c = 2 * atan2(sqrt(a), sqrt(1-a));
    
            return R * c;
        END$$
    
    DELIMITER ;
    

    盗自:https://www.bram.us/2018/03/01/mysql-st_distance_sphere-polyfill/

    【讨论】:

      猜你喜欢
      • 2018-11-18
      • 1970-01-01
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      相关资源
      最近更新 更多