2

我有一个 PostGIS 查询,我确实需要在 PostGIS 函数调用中进行嵌套查询:

UPDATE raw.geocoding
SET the_geom = ST_Centroid(
   ST_Collect(
     SELECT the_geom
     FROM raw.geocoding
     WHERE hash = ((E'0101000020090C000081610F9CC5DC3341EE672E6E723B3241')::varchar),
     SELECT the_geom
     FROM raw.geocoding
     WHERE hash = ((E'0101000020090C00002CF887E0C5DC3341C9E5B2DF2A383241')::varchar)
    )
  )
WHERE hash = ((E'3e638a27c6c38f05026252f4a0b57b2e')::varchar)

不幸的是,这不起作用。在嵌套查询开始时出现语法错误:

ERROR:  syntax error at or near "SELECT"
LINE 4:          SELECT the_geom
                 ^

********** Error **********

ERROR: syntax error at or near "SELECT"
SQL state: 42601
Character: 86

看起来我不能将嵌套查询作为 PostGIS 函数参数?

我仔细阅读了 PostGIS 文档,但找不到任何明确的指导来处理这个问题。

似乎 Postgres 有一种在 pgSQL 中处理变量的方法,但我不清楚如何在标准查询中实现这一点。这是一个将从 C# 程序运行数万或数十万次的查询。除此之外,如果需要,我可以执行 pgSQL 存储过程;只是想先确定没有更简单的替代方案。

如果您想知道,查询看起来很混乱,因为它是 npgsql 生成的参数化查询的结果。我认为可以公平地说 npgsql 对多余的输入和转义非常谨慎。

我正在运行 PostGIS 2.0.1、Postgres 9.1.5 和 npgsql 2.0.12。

4

1 回答 1

3

It sounds like you want a scalar subquery, an expression written like (SELECT ....) (note enclosing parentheses) that contains a query returning either zero rows (NULL result) or one field from one row.

You were most of the way there, you just needed the parens:

UPDATE raw.geocoding
SET the_geom = ST_Centroid(
   ST_Collect(
     (SELECT the_geom
     FROM raw.geocoding
     WHERE hash = ((E'0101000020090C000081610F9CC5DC3341EE672E6E723B3241')::varchar)),
     (SELECT the_geom
     FROM raw.geocoding
     WHERE hash = ((E'0101000020090C00002CF887E0C5DC3341C9E5B2DF2A383241')::varchar))
    )
  )
WHERE hash = ((E'3e638a27c6c38f05026252f4a0b57b2e')::varchar)

Note that subqueries can be used in other places too - table returning subqueries can appear in FROM, for example. The PostgreSQL manual teaches about all this, and is well worth a cover-to-cover read.

If you're doing a lot of these updates, you may find it more efficient to formulate the UPDATE as a join using the PostgreSQL extension UPDATE ... FROM ... WHERE rather than running lots of individual UPDATEs over and over. I just wanted to raise the possibility. See from-list in UPDATE

于 2012-09-17T02:45:29.697 回答