如何更新几何列与合并线串基于数组的他们的id在PostgreSQL?

ddrv8njm  于 2022-11-23  发布在  PostgreSQL
关注(0)|答案(1)|浏览(129)

我有两个数据表。一个包含线串几何及其id。另一个包含第一个表中的线id数组。在某些情况下,数组中只有一个id,在其他情况下,数组中有多个id,但基本上可以是任何数字。有一点是肯定的,数组中的线串在其端点处连接。
如果数组属性中有多个id,我希望根据它们的id合并线串。如果只有一个id,我希望复制原始几何图形。
下面是两个示例表。(为了更好地理解,我添加了一个具有WKT几何结构的geom_astext列。)

CREATE TABLE me.test_lines
(gid serial PRIMARY KEY,
the_geom geometry(LineString,4326));

INSERT INTO me.test_lines (the_geom)
VALUES 
(ST_MakeLine(ST_Point(1,2), ST_Point(3,4))),
(ST_MakeLine(ST_Point(0,0), ST_Point(2,2))),
(ST_MakeLine(ST_Point(2,2), ST_Point(2,4))),
(ST_MakeLine(ST_Point(2,4), ST_Point(3,4))),
(ST_MakeLine(ST_Point(5,5), ST_Point(6,6))),
(ST_MakeLine(ST_Point(6,2), ST_Point(4,0)));

CREATE TABLE me.test_lines_merged
(id serial PRIMARY KEY,
 gid_array int[],
the_geom geometry(LineString,4326))
geom_astext text;

INSERT INTO me.test_lines_merged (gid_array)
VALUES 
('{1}'),
('{2,3,4}'),
('{5}'),
('{6}');

我的测试行:

gid geom_astext
1   "LINESTRING(1 2,3 4)"
2   "LINESTRING(0 0,2 2)"
3   "LINESTRING(2 2,2 4)"
4   "LINESTRING(2 4,3 4)"
5   "LINESTRING(5 5,6 6)"
6   "LINESTRING(6 2,4 0)"

合并的测试行

id  gid_array   geom_astext
1   {1} 
2   {2,3,4} 
3   {5} 
4   {6}

我想要的是:

id  gid_array geom_astext
1   {1}       "LINESTRING(1 2,3 4)"
2   {2,3,4}   "LINESTRING(0 0,2 2,2 4,3 4)"
3   {5}       "LINESTRING(5 5,6 6)"
4   {6}       "LINESTRING(6 2,4 0)"

我知道如何更新只有一个数组元素的几何图形:

UPDATE me.test_lines_merged a
SET the_geom = b.the_geom,
geom_astext = ST_AsText(b.the_geom)
FROM me.test_lines b
WHERE a.gid_array[1] = b.gid
AND array_length(a.gid_array,1) = 1

我也有一个关于如何合并行的想法,但我只能使它只为一行:

UPDATE me.test_lines_merged 
SET the_geom = b.the_geom,
geom_astext = (SELECT ST_AsText(ST_MakeLine(the_geom)) 
FROM me.test_lines b 
WHERE gid in 
    (SELECT UNNEST(gid_array) FROM me.test_lines_merged WHERE id = 2))
vaqhlq81

vaqhlq811#

若要取得所需的缐条,您必须根据目的数组(ANY())中出现的ID来链接两个数据表。然后,您必须依目的ID和union将区段分组,以建立多缐条,然后套用st_line_merge将区段“缝合”成简单的缐条。

SELECT tlm.id, st_asText(ST_LineMerge(st_union(tl.the_geom)))
FROM  test_lines_merged tlm
 JOIN test_lines tl
  ON tl.gid = ANY(tlm.gid_array)
GROUP BY tlm.id;

 id |          st_astext
----+-----------------------------
  1 | LINESTRING(1 2,3 4)
  2 | LINESTRING(0 0,2 2,2 4,3 4)
  3 | LINESTRING(5 5,6 6)
  4 | LINESTRING(6 2,4 0)

从那里,您可以在更新语句中使用此查询,将目标表联接到此子查询:

UPDATE test_lines_merged
SET the_geom = sub.merged_geom,
     geom_astext = st_asText(sub.merged_geom)
FROM (
 SELECT tlm.id, 
        ST_LineMerge(st_union(tl.the_geom)) AS merged_geom
 FROM  test_lines_merged tlm
   JOIN test_lines tl
   ON tl.gid = ANY(tlm.gid_array)
 GROUP BY tlm.id
) AS sub
WHERE test_lines_merged.id = sub.id;

相关问题