gpt4 book ai didi

用于计算坐标邻近度的 SQL 查询

转载 作者:行者123 更新时间:2023-12-04 10:59:44 25 4
gpt4 key购买 nike

我正在使用这个公式来计算我的 (My)SQL 数据库中具有十进制格式的纬度和经度字段的条目之间的距离:

6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + 
COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) -
RADIANS( %lon1% )))
适本地替换 %lat1% 和 %lat2% 可以在 WHERE 子句中使用它来查找另一个条目特定半径内的条目,在 ORDER BY 子句中与 LIMIT 一起使用将找到最近的 x 个条目等。
我写这篇文章主要是为了给自己做笔记,但总是欢迎改进。 :)
注意:正如下面 Valerion 提到的,这以公里计算。用 appropriate alternative number 代替 6371使用米、英里等。

最佳答案

对于不支持三角函数的数据库(如 SQLite),您可以使用勾股定理。
这是一种更快的方法,即使您的数据库确实支持三角函数,但有以下注意事项:

  • 您需要将坐标存储在 x,y 网格中,而不是(或以及)lat,lng;
  • 计算假设为“平坦的地球”,但这对于相对本地的搜索来说很好。

  • 这是我正在处理的 Rails 项目中的一个示例(重要的是中间的 SQL):
    class User < ActiveRecord::Base
    ...
    # has integer x & y coordinates
    ...

    # Returns array of {:user => <User>, :distance => <distance>}, sorted by distance (in metres).
    # Distance is rounded to nearest integer.
    # point is a Geo::LatLng.
    # radius is in metres.
    # limit specifies the maximum number of records to return (default 100).
    def self.find_within_radius(point, radius, limit = 100)

    sql = <<-SQL
    select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d
    from users where #{(radius ** 2)} >= d
    order by d limit #{limit}
    SQL

    users = User.find_by_sql(sql)
    users.each {|user| user.d = Math.sqrt(user.d.to_f).round}
    return users
    end

    关于用于计算坐标邻近度的 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/91116/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com