如何在PostgreSQL / Postgis中加入两个具有不相等结果(不同列和行)的查询

时间:2017-06-06 20:44:52

标签: postgresql postgis postgresql-9.5

在我的PostgreSQL / PostGIS数据库中,我有两个不同结果的查询。

查询1:

With buffer as 
(
    SELECT   gid, 
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp 
    group by gid, geom --cp being point layer with one row
    UNION ALL 
    SELECT   gid, 
             geom 
    FROM     cp        --cp being point layer with only one row
)
SELECT   gid,
         generate_series(1,12) id,
         (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
FROM     buffer
group by gid
order by gid, id

返回包含12行的三列(gid,id,geom)。而query2:

With buffer as 
(
    SELECT   gid, 
             (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
    FROM     cp 
    group by gid, geom --cp being the same point layer
    UNION ALL 
    SELECT   gid, 
             geom 
    FROM     cp        -- cp being the same point layer
)
Select distinct geom as pts, 
       gid 
from   buffer

返回包含13行的两列(pts,gid)。我想在gid的基础上加入这两个查询,因为我想为大量的点自动化这个过程。我记得,第一个查询返回点周围的12个段/行(三角形/饼状楔形几何)(cp,gid = 1)。第二个查询返回这些三角形的外顶点(13个点)。我需要最有效地加入这些查询,以便所需的输出应该产生四列,如:

 gid, id, geom, pts
 1    1   xxx   yyy
 1    2   xxx   yyy
 1    3   xxx   yyy
 1    4   xxx   yyy
 1    5   xxx   yyy
 1    6   xxx   yyy
 1    7   xxx   yyy
 1    8   xxx   yyy
 1    9   xxx   yyy
 1    10  xxx   yyy
 1    11  xxx   yyy
 1    12  xxx   yyy
 1    13  NULL  yyy

任何人都可以帮我加入上述两个查询的不平等结果吗?任何指针都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

尝试这样(我只是CTE你的语句和外部加入他们):

with a as (
    With buffer as 
    (
        SELECT   gid, 
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp 
        group by gid, geom --cp being point layer with one row
        UNION ALL 
        SELECT   gid, 
                 geom 
        FROM     cp        --cp being point layer with only one row
    )
    SELECT   gid,
             generate_series(1,12) id,
             (ST_Dump(ST_DelaunayTriangles(ST_Collect(geom),0, 0))).geom as geom
    FROM     buffer
    group by gid
    order by gid, id
)
, b as (

    With buffer as 
    (
        SELECT   gid, 
                 (ST_DumpPoints(ST_Buffer(geom,50,3))).geom as geom
        FROM     cp 
        group by gid, geom --cp being the same point layer
        UNION ALL 
        SELECT   gid, 
                 geom 
        FROM     cp        -- cp being the same point layer
    )
    Select distinct geom as pts, 
           gid 
           , row_number() over () as id
    from   buffer
)
select * 
from b
left outer join a on b.gid = a.gid and b.id = a.id
;