How to merge polygons that share some features
If the same "original" shape has the same cat
and unid
in both tables, you can just UNION
the tables, then ST_Union()
the shapes back together, grouping by cat
and unid
:
create table hrl_tst.your_shapes_back_together as
with both_tiles as (table hrl_tst.tile1 union all table hrl_tst.tile2)
select cat
,unid
,st_union(geom) as geom
from both_tiles
group by cat,unid;
This will use the aggregate variant of ST_Union()
and dissolve all shapes that share the same unid
and cat
from both tables at the same time.
Your example used two-variant ST_Union()
in STEP 1 that kept only dissolving two shapes at a time and in STEP 2 you merged those pairs into groups sharing one common shape, which is still a few steps away from dissolving the whole group.
How to merge polygons that touch and share some features
create table hrl_tst.your_shapes_back_together as
with both_tiles as (table hrl_tst.tile1 union all table hrl_tst.tile2)
,clustered as (
select *,ST_ClusterDBSCAN(geom,0,1)over(partition by cat) c_num
from both_tiles)
select cat
,unid
,st_makevalid(st_union(geom)) as geom --it's healthy to `st_makevalid()`
from clustered
group by cat,unid,c_num;
Problems withAbout your initial approach