psycopg2.ProgrammingError:无法将类型记录转换为几何体

时间:2016-06-21 12:14:48

标签: python sql postgresql postgis

我有一个查询从线串中找到最近的POI。查询是这样的:

import psycopg2

conn = psycopg2.connect("dbname=TestGIS user=postgis")
cur = conn.cursor()

cur.execute("SELECT poi.name,poi.city,ST_AsTEXT(poi.the_geog),
            ST_AsText(ST_ClosestPoint(road.the_geog::geometry, poi.the_geog::geometry)),
            ST_Distance_Sphere(ST_ClosestPoint(road.the_geog::geometry, poi.the_geog::geometry), poi.the_geog::geometry)/1000 
            AS Distance FROM road, poi WHERE road.id = 123 AND
            ST_DWithin(road.the_geog, poi.the_geog, 1000.0) ORDER BY
            ST_LineLocatePoint(road.the_geog::geometry, poi.the_geog::geometry), 
            ST_Distance(road.the_geog, poi.the_geog);")

现在我想执行相同的查询,但在同一查询中提供了线串(road)。像这样:

cur.execute("
    SELECT
        poi.name,poi.city,ST_AsTEXT(poi.the_geog),
        ST_AsText(ST_ClosestPoint(road::geometry, poi.the_geog::geometry)),
        ST_Distance_Sphere(ST_ClosestPoint(road::geometry, poi.the_geog::geometry), poi.the_geog::geometry)/1000 AS Distance
    FROM (
        SELECT ST_GeographyFromText(
            'SRID=4326;LINESTRING(85.280194 23.296728,85.281572 23.297479)'
            )
        ) AS road, poi
    WHERE
        ST_DWithin(road, poi.the_geog, 1000.0) ORDER BY
        ST_LineLocatePoint(road::geometry, poi.the_geog::geometry), 
        ST_Distance(road, poi.the_geog);
")

但是我收到了这个错误:

psycopg2.ProgrammingError: cannot cast type record to geometry
LINE 1: ...sTEXT(poi.the_geog),ST_AsText(ST_ClosestPoint(road::geometry...

谁能告诉我我做错了什么?

更新: 该表是:

cur.execute("CREATE TABLE poi(gid serial PRIMARY KEY, name varchar, city varchar, the_geog geography(POINT,4326) );")
cur.execute('''INSERT INTO poi (gid, name, city, the_geog) VALUES (%s,%s, %s,ST_GeogFromText(%s))''',(int(count),row[0],row[1],coordinates))

1 个答案:

答案 0 :(得分:0)

为列添加别名,以便您可以引用它:

FROM (
    SELECT ST_GeographyFromText(
        'SRID=4326;LINESTRING(85.280194 23.296728,85.281572 23.297479)'
    ) as road
) AS road