当一个不存在时,如何使此查询返回结果?

时间:2012-07-16 19:31:56

标签: sql postgresql join postgis

Poly1是一个边界框,用于计算落在其边界内的f1和f2的面积。如果存在f1,如何使此查询返回结果,但f2不存在?现在,如果边界框内只有f1,则查询不返回任何结果。

SELECT ST_Transform(poly1.the_geom,3857) AS the_geom_webmercator, 
       ST_AREA(ST_Union(ST_Transform(ST_Intersection(f1.the_geom,poly1.the_geom),3857)))*.000247105381 AS acreage_of_1,
       ST_AREA(ST_Union(ST_Transform(ST_Intersection(f2.the_geom,poly1.the_geom),3857)))*.000247105381 AS acreage_of_2
            FROM poly1 JOIN farmland f1 ON f1.polygon_type = 'A' AND
                                           st_intersects(f1.the_geom,poly1.the_geom)
                       JOIN farmland f2 ON f2.polygon_type = 'B'
            GROUP BY poly1.the_geom

1 个答案:

答案 0 :(得分:1)

您希望在“farmland f2”语句之前使用左外连接。左外连接将保留所有行,即使f2中没有匹配项:

Select ST_Transform(poly1.the_geom,3857) as the_geom_webmercator, 
       ST_AREA(ST_Union(ST_Transform(ST_Intersection(f1.the_geom,poly1.the_geom),3857)))*.000247105381 AS acreage_of_1,
       ST_AREA(ST_Union(ST_Transform(ST_Intersection(f2.the_geom,poly1.the_geom),3857)))*.000247105381 AS acreage_of_2
FROM poly1 JOIN
     farmland f1
     ON f1.polygon_type = 'A' AND st_intersects(fp.the_geom,poly1.the_geom) **LEFT OUTER** JOIN
     farmland f2
     ON f2.polygon_type = 'B'
 group by poly1.the_geom