POSTGRESQL,无子查询:FROM 中的子查询必须有别名

POSTGRESQL, No Subquery: subquery in FROM must have an alias

据我所知,我正在使用计算字段和空间查询查询数据库,但没有任何子查询。但是,POSTGRESQL 一直要求我提供别名....

 SELECT geoid as destination, 
    lehd_graph.h_geocode asorigin,lehd_graph.S000 as population,
    (ST_buffer(ST_Transform(ST_SetSRID(ST_Point(-74.01128768920898, 40.739843698929995), 4326), 3857), 500)))  /
ST_area(lehd_map.the_geom_webmercator)) as fraction 
FROM lehd LEFT JOIN lehd_graph 
ON lehd.w_geocode = lehd_graph.w_geocode 
WHERE ST_intersects( lehd_map.the_geom_webmercator, 
ST_buffer(ST_Transform( ST_SetSRID(ST_Point(-74.01128768920898, 40.739843698929995), 4326), 3857), 500))

语法错误:FROM 中的子查询必须有别名

您的查询有几个问题。直接错误是由于第一次调用 ST_Buffer() 时括号数量不匹配引起的,但即使更正了你的查询也不会执行;事实上,第一个调用是一种非常昂贵的方法,它不精确地计算半径为 500 米的圆的面积 - 正好是 785398.163 平方米 - 所以你可以摆脱那个调用并插入该区域。 (现在不再相关的另一个问题是,您试图将 geometry 除以 ST_Area() 的标量值,这显然是不可能的。)

另一个问题是您没有在 FROM 子句中包含 table lehd_map;我通过 JOIN 添加到这里。

SELECT geoid AS destination, 
       lehd_graph.h_geocode AS origin,
       lehd_graph.S000 AS population,
       785398.163 / ST_Area(lehd_map.the_geom_webmercator)) AS fraction 
FROM lehd
LEFT JOIN lehd_graph USING (w_geocode)
JOIN lehd_map ON ST_Intersects(lehd_map.the_geom_webmercator, 
                   ST_Buffer(
                     ST_Transform(
                       ST_SetSRID(
                         ST_Point(-74.01128768920898, 40.739843698929995),
                         4326),
                       3857),
                     500)
                   );

如果你觉得分离点的缓冲区和缓冲区的区域不方便,那么你可以将它们组合在一个CTE中,以强调区域与缓冲点的关系:

WITH pt(geom, area) AS (
    VALUES (ST_Buffer(
              ST_Transform(
                ST_SetSRID(
                  ST_Point(-74.01128768920898, 40.739843698929995), 4326), 3857), 500),
            785398.163) -- 500 x 500 x pi: area of the buffer around the point
)
SELECT geoid AS destination, 
       lehd_graph.h_geocode AS origin,
       lehd_graph.S000 AS population,
       pt.area / ST_Area(lehd_map.the_geom_webmercator) AS fraction 
FROM pt
JOIN lehd ON true
LEFT JOIN lehd_graph USING (w_geocode)
JOIN lehd_map ON ST_Intersects(lehd_map.the_geom_webmercator, pt.geom);