使用 MySql 或 Postgres 获取给定半径内的日志

Get logs within a given radius with MySql or Postgres

我有以下 table,其中纬度和经度字段指定地图上的一个点。

|id   |latitud         |longitud         |
| --- | ------ --------| ---------------- | 
| 001 |19.4400570537131|-99.1270470974249 | 
| 002 |19.437904276995 |-99.1286576775023 |
| 003 |19.4360705910348|-99.1297865731994 |
| 001 |19.4424869116657|-99.1238332599196 |

我需要查询 returns 点 (19.4400570537131, -99.1270470974249) 周围 1000 米半径内的记录数。

如果MySQL不行,我可以用PostgreSQL

在 PostgreSQL(带有 PostGIS)中,您要查找的函数在查询时被称为 ST_DWithin. To use it with metres you either have to ST_Transform your coordinates to a SRS that has metre as unit or use geography instead of geometry. The example below creates a point with ST_MakePoint,将其转换为 geography 并使用 ST_DWithin 和点应用过滤器您的问题中提到的半径为 1000 米。

WITH j (id,lat,lon) AS ( VALUES
  (001,19.4400570537131,-99.1270470974249),
  (002,19.437904276995 ,-99.1286576775023),
  (003,19.4360705910348,-99.1297865731994),
  (001,19.4424869116657,-99.1238332599196)
) 
SELECT 
  id,
  ST_Distance(
    ST_MakePoint(lon,lat)::geography,
    ST_MakePoint(-99.1270470974249,19.4400570537131)::geography) AS distance,
  ST_MakePoint(lon,lat)::geography AS geom
FROM j 
WHERE ST_DWithin(
        ST_MakePoint(lon,lat)::geography,
        ST_MakePoint(-99.1270470974249,19.4400570537131)::geography,1000);

 id |   distance   |                        geom                        
----+--------------+----------------------------------------------------
  1 |            0 | 0101000020E6100000781F268A21C858C067123E94A7703340
  2 | 292.22521599 | 0101000020E61000001C5069ED3BC858C0D878A47E1A703340
  3 |   526.781174 | 0101000020E61000007CD6576C4EC858C0EA3D7F52A26F3340
  1 |  431.5655003 | 0101000020E6100000C16056E2ECC758C021837ED246713340

注意:我强烈建议您将这些点存储在geometrygeography 列中,并正确索引它们。在查询时使用分离的纬度和经度值创建几何图形会产生不必要的开销,并且可能会显着降低查询速度。此外,如果您不在显微镜领域工作,请考虑降低点的精度;)

延伸阅读: