【问题标题】:How to find near stores from store location (latitude, longitude) from store table?如何从商店表中的商店位置(纬度,经度)找到附近的商店?
【发布时间】:2021-10-22 11:27:20
【问题描述】:

我有一个名为 stores 的 Postgresql 表,其中包含商店的位置(纬度、经度),我可以使用查询从商店中找到附近的商店。但是,我找不到创建“就绪”生成表的查询,该表为每个商店创建附近商店列表。 这是我用来获取附近商店列表的查询:

select mds.id, mds.store_name
    from public.store mds,
    (select latitude, longitude from public.store where id = '3f6077c0-c56b-4570-883f-4c16dc19855e') as st,
    sqrt(111.12 * (mds.latitude - st.latitude) * 111.12 * (mds.latitude - st.latitude) + (111.12 * (mds.longitude - st.longitude) * cos(st.latitude / 92.215)) * (111.12 * (mds.longitude - st.longitude) * cos(st.latitude / 92.215))) as distance
where distance <= 20
order by distance
limit 100

我无法将“3f6077c0-c56b-4570-883f-4c16dc19855e”替换为 public.store.id。 store表的表列是:

| id  | store_name  | latitude   |  longitude  |

请帮我处理这个请求。非常感谢。

【问题讨论】:

    标签: sql postgresql postgis


    【解决方案1】:

    使用扩展名PostGIS 可以更好地处理空间查询。它有很多非常方便的功能,使空间查询非常容易编写和维护。我的建议:

    安装 Postgis(见其他 answer

    在表格中添加几何列,例如

    SELECT AddGeometryColumn ('public','store','geom',4326,'POINT',2);
    

    根据您的纬度和经度值创建点几何图形:

    UPDATE store SET geom = ST_MakePoint(longitude,latitude);
    

    索引它(使查询更快)

    CREATE INDEX idx_store_geom ON store USING gist (geom);
    

    之后,列出给定点最近邻居的查询如下所示:

    SELECT * FROM store
    ORDER BY geom <-> ST_SetSRID(ST_MakePoint(92.215,111.12),4326)
    

    或者,如果您想要离每家商店最近的商店..

    SELECT * FROM store mds,
    LATERAL (SELECT store_name,ST_Distance(geom,mds.geom) FROM store
             WHERE id <> mds.id
             ORDER BY geom <-> mds.geom
             LIMIT 1) c (closest_store,distance);
    
    • 运算符&lt;-&gt; 代表距离,因此在ORDER BY 子句和LIMIT 1 中使用它只会选择最接近参考几何的记录。
    • 4326 代表空间参考系统WGS84。它可能会因您的坐标而异。

    演示:db&lt;&gt;fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      相关资源
      最近更新 更多