如何将此子查询优化为连接?

Joh*_*ohn 5 sql postgresql optimization postgis

我注意到运行这个子查询

SELECT ST_Area(ST_Union(ST_Transform(ST_Intersection((SELECT poly1.the_geom from poly1 WHERE poly1.polygon_type ='P'),poly2.the_geom),3857)))

AS area_of_P FROM poly1,poly2

比运行此连接要慢得多

SELECT ST_AREA(ST_Union(ST_Transform(ST_Intersection(poly1.the_geom,poly2.the_geom),3857)))

AS area_of_poly

来自poly2

在st_intersects上左边连接poly1(poly1.the_geom,poly2.the_geom)

在哪里poly2.polygon_type ='P'

但是,我需要扩展这个第二个连接版本以返回更多列,每个列都计算出给定多边形类型的区域,即

SELECT ST_Area(ST_Union(ST_Transform(ST_Intersection((SELECT poly1.the_geom from poly1 WHERE poly1.polygon_type ='P'),poly2.the_geom),3857)))AS area_of_P,

ST_Area(ST_Union(ST_Transform(ST_Intersection((SELECT poly1.the_geom from poly1 WHERE poly1.polygon_type ='S'),poly2.the_geom),3857)))AS area_of_S

来自poly1,poly2

Bre*_*ker 6

试试这个.

SELECT ST_AREA(ST_Union(ST_Transform(ST_Intersection(poly1.the_geom,poly2.the_geom),3857)))

AS area_of_poly

FROM poly2

LEFT JOIN poly1 on st_intersects(poly1.the_geom,poly2.the_geom)

WHERE poly2.polygon_type IN ( 'P', 'S' )
Run Code Online (Sandbox Code Playgroud)

编辑:

SELECT ST_AREA(ST_Union(ST_Transform(ST_Intersection(ps.the_geom,poly2.the_geom),3857))) AS area_of_P,
       ST_AREA(ST_Union(ST_Transform(ST_Intersection(ss.the_geom,poly2.the_geom),3857))) AS area_of_S
FROM poly2
JOIN poly1 ps ON poly2.polygon_type = 'P' AND st_intersects(ps.the_geom,poly2.the_geom)
JOIN poly1 ss ON poly2.polygon_type = 'S' AND st_intersects(ss.the_geom,poly2.the_geom)
Run Code Online (Sandbox Code Playgroud)