运算符不存在:geography< - >地理

时间:2015-07-28 21:33:26

标签: postgresql postgis

我的postgresql列类型为

geography(Point,4326)

我已经使用

插入了一些行
POINT(LONG LAT)

已成功插入数据并且我可以毫无问题地检索它,现在我想使用以下查询获取最近的条目到特定点

SELECT "cafes".* FROM "cafes" ORDER BY "latlng" <-> (SELECT latlng FROM cafes WHERE id = '3') LIMIT 1

但是我收到以下错误

ERROR:  operator does not exist: geography <-> geography
LINE 1: ...es".* FROM "cafes" ORDER BY "latlng" <-> (SELEC...
                                                         ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

1 个答案:

答案 0 :(得分:2)

The <-> "distance between" operator applies to PostgreSQL geometric data types, not to the PostGIS geography data type. With the geography data type you can use the PostGIS function ST_Distance() and find the minimum value.

WITH this_cafe (latlng) AS (
  SELECT latlng FROM cafes WHERE id = '3'
)
SELECT cafes.*, ST_Distance(cafes.latlng, this_cafe.latlng, 'false') AS dist
FROM cafes, this_cafe
ORDER BY dist ASC
LIMIT 1

Note that the third argument useSpheroid to the function is set to false which will make the function much faster. It is unlikely going to affect the result because cafes tend to lie close to each other.

This assumes that there is only 1 cafe with id = 3. If there could be more, then restrict the CTE to return just 1 row.