在SQLAlchemy中为子查询添加别名

时间:2014-09-16 17:59:14

标签: python sqlalchemy subquery polygon postgis

过去2小时这让我疯了:

我试图查询重叠的多边形。这与PostGIS函数很好地配合,但我很难用SQLAlchemy编写这个查询。

正确的SQL查询是:

SELECT id FROM track WHERE ST_Overlaps(
  (
    SELECT ST_GeomFromText(
      'POLYGON((
        16.15 47.25, 
        16.15 46.57, 
        13.85 46.57, 
        13.85 47.25, 
        16.15 47.25
      ))', 
    4326)
  ), 
  track.extent
);

track.extent 是一个以地理格式保存多边形的列, ST_GeomFromText() 创建多边形我将它们与之比较

我正在使用ORM,到目前为止,我的python代码看起来像这样:

viewport = select([func.ST_GeomFromText(('POLYGON(( \
  16.15 47.25, \
  16.15 46.57, \
  13.85 46.57, \
  13.85 47.25, \
  16.15 47.25))' \
  ,4326))])

DBSession.query(Track.id).filter( \
  func.ST_Overlaps(viewport, Track.extent)).all()

上面的代码由SQLAlchemy解释为以下SQL-Query:

SELECT track.id AS track_id FROM track, 
(SELECT ST_GeomFromText('
  POLYGON((
    16.15 47.25, 
    16.15 46.57, 
    13.85 46.57, 
    13.85 47.25, 
    16.15 47.25
  ))', 
  4326) AS "ST_GeomFromText_1"
) 
WHERE ST_Overlaps(
  (
    SELECT ST_GeomFromText(
      'POLYGON((
        16.15 47.25, 
        16.15 46.57, 
        13.85 46.57, 
        13.85 47.25, 
        16.15 47.25
      ))', 
      4326) AS "ST_GeomFromText_1"
    ), 
  track.extent
);

产生错误:

 ProgrammingError: (ProgrammingError) subquery in FROM must have an alias
 LINE 2: FROM track, (SELECT ST_GeomFromText('POLYGON((16.15759034023...
                     ^
 HINT:  For example, FROM (SELECT ...) [AS] foo.

我如何告诉sqlalchemy在FROM子句中删除不必要的 viewport -subquery,或者为 视口添加别名 -query?

1 个答案:

答案 0 :(得分:1)

我相信您正在寻找.label()构造:

viewport = select([func.ST_GeomFromText(...)]).label("viewport")

然后,将它放在WHERE子句中也不会将它放在FROM子句中:

str(session.query(Track.id).filter(func.ST_Overlaps(viewport, Track.extent))
# 'SELECT track.id AS track_id \nFROM track \nWHERE ST_Overlaps((SELECT ST_GeomFromText(...) AS "ST_GeomFromText_1"), track.extent)'