← 中文资源

简体中文版本

半正矢距离找最近门店

不装 PostGIS 也能找最近门店:半正矢公式用 radians/sin/cos/asin 把经纬度换成球面距离,按距离升序 LIMIT 取前三。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 depots。 用到的 SQL 构件:ORDER BY 固定了输出顺序;LIMIT 限制返回行数;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY。

常见问题

这里用到哪些关系?

depots。

核心语句

SELECT
    depot_id,
    depot_name,
    ROUND((2.0 * 6371.0 * ASIN(SQRT(
        POWER(SIN(RADIANS(40.7580 - lat) / 2), 2)
        + COS(RADIANS(lat)) * COS(RADIANS(40.7580))
        * POWER(SIN(RADIANS(-73.9855 - lng) / 2), 2)
    )))::numeric, 1) AS distance_km
FROM depots
ORDER BY distance_km
LIMIT 3;
INSERT INTO depots VALUES
    (1, 'harbor',   40.7000, -74.0100),
    (2, 'midtown',  40.7610, -73.9770),
    (3, 'uptown',   40.8100, -73.9500),
    (4, 'brooklyn', 40.6800, -73.9400);
CREATE TABLE depots (
    depot_id   int PRIMARY KEY,
    depot_name text NOT NULL,
    lat        double precision NOT NULL,
    lng        double precision NOT NULL
);

代码示例

-- haversine formula: great-circle distance between two points in kilometers (Earth radius 6371 km)
-- the usual approximation without PostGIS: storing lat/lng as double precision is enough
CREATE TABLE depots (
    depot_id   int PRIMARY KEY,
    depot_name text NOT NULL,
    lat        double precision NOT NULL,
    lng        double precision NOT NULL
);

INSERT INTO depots VALUES
    (1, 'harbor',   40.7000, -74.0100),
    (2, 'midtown',  40.7610, -73.9770),
    (3, 'uptown',   40.8100, -73.9500),
    (4, 'brooklyn', 40.6800, -73.9400);

-- target point: Times Square (40.7580, -73.9855)
-- distance = 2 * R * asin(sqrt(sin²(Δφ/2) + cosφ1·cosφ2·sin²(Δλ/2)))
-- rank depots nearest first: ORDER BY ascending + LIMIT
SELECT
    depot_id,
    depot_name,
    ROUND((2.0 * 6371.0 * ASIN(SQRT(
        POWER(SIN(RADIANS(40.7580 - lat) / 2), 2)
        + COS(RADIANS(lat)) * COS(RADIANS(40.7580))
        * POWER(SIN(RADIANS(-73.9855 - lng) / 2), 2)
    )))::numeric, 1) AS distance_km
FROM depots
ORDER BY distance_km
LIMIT 3;