您好,我正在尝试在 postgresql 数据库中按纬度和经度查找最近的位置。但是当我运行以下查询时,它显示列距离不存在。
ERROR: column "distance" does not exist
LINE 1: ... ) ) ) AS distance FROM station_location HAVING distance <...
^
********** Error **********
ERROR: column "distance" does not exist
SQL state: 42703
Character: 218
CREATE TABLE station_location
(
id bigint NOT NULL DEFAULT nextval('location_id_seq'::regclass),
state_name character varying NOT NULL,
country_name character varying NOT NULL,
locality character varying NOT NULL,
created_date timestamp without time zone NOT NULL,
is_delete boolean NOT NULL DEFAULT false,
lat double precision,
lng double precision,
CONSTRAINT location_pkey PRIMARY KEY (id)
)
SELECT *,( 3959 * acos( cos( radians(6.414478) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(12.466646) ) + sin( radians(6.414478) ) * sin( radians( lat ) ) ) ) AS distance
FROM station_location
HAVING distance < 5
ORDER BY distance
LIMIT 20;
最佳答案
后地理信息系统
不要在这样的 table 上存储经纬度。而是使用 PostGIS 几何或 geography type .
CREATE EXTENSION postgis;
CREATE TABLE foo (
geog geography;
);
CREATE INDEX ON foo USING gist(geog);
INSERT INTO foo (geog)
VALUES (ST_MakePoint(x,y));
现在需要查询的时候可以用KNN ( <->
)这实际上会在索引上执行此操作。
SELECT *
FROM foo
ORDER BY foo.geog <-> ST_MakePoint(x,y)::geography;
在您的查询中,您明确拥有 HAVING distance < 5
.您也可以在索引上执行此操作。
SELECT *
FROM foo
WHERE ST_DWithin(foo.geog, ST_MakePoint(x,y)::geography, distance_in_meters)
ORDER BY foo.geog <-> ST_MakePoint(x,y)::geography;
如果所有点都在 distance_in_meters
之外,这将确保不会返回任何内容.
另外x和y是十进制数ST_MakePoint(46.06, 14.505)
关于sql - 在postgresql中按经纬度查找最近的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827468/