簡體   English   中英

執行 UNNEST、INNER JOIN 和 ARRAY_AGG 作為 UPDATE 查詢的一部分

[英]Perform UNNEST, INNER JOIN and then ARRAY_AGG as part of an UPDATE query

我正在嘗試使用 ORDINALITY 從一個表中取消嵌套數組以保留順序,然后在另一個表上執行 INNER JOIN 以從特定列中查找相應的值,然后使用 ARRAY_AGG 將其打包並更新原始表。 我有一些適用於單個查詢的東西,但我想對表中的每一行進行更新,但似乎無法讓它工作。 我覺得我很接近,但我在這方面花了太長時間,所以任何幫助都將不勝感激。

下面是生成表格的代碼,以及我正在尋找的答案和我的嘗試。

create table table_1(
    table_1_id int,
    table_2_id_list int[],
    table_2_geom text[]
);

insert into table_1 values 
    (1, ARRAY[1,3,5], null) ,(2, ARRAY[2,4,6], null);

create table table_2(table_2_id int, geom text);
insert into table_2 values
    (1, 'geom1'), (2, 'geom2'), (3, 'geom3'),
    (4, 'geom4'), (5, 'geom5'), (6, 'geom6');

我想以這樣的方式結束:

table_1_id  | table_2_id_list  | table_2_geom
------------------------------------------------------------------
1           | (1, 3, 5)        |  (geom1, geom3, geom5) 
2           | (2, 4, 6)        |  (geom2, geom4, geom6) 

我可以使用以下方法使其適用於單個案例:

SELECT 
    TABLE_1_ID, 
    array_agg(TABLE_2.geom ORDER BY ORDINALITY) 
FROM TABLE_1, 
unnest(table_2_id_list) WITH ORDINALITY a 
INNER JOIN TABLE_2 ON a = TABLE_2.TABLE_2_ID 
GROUP BY TABLE_1_ID LIMIT 1;

但是當我嘗試執行類似於 UPDATE 表中每一行的操作時,我做錯了。 我已經嘗試了以下但它不起作用:

UPDATE TABLE_1
SET table_2_geom = (
    SELECT array_agg(TABLE_2.geom ORDER BY ORDINALITY) 
    FROM TABLE_1, 
    unnest(table_2_id_list) WITH ORDINALITY a 
    INNER JOIN TABLE_2 ON a = TABLE_2.TABLE_2_ID
); 

如果有人能指出我正確的方向,我將不勝感激。

謝謝

您可以將現有查詢轉換為 CTE 並將其與原始表連接以進行更新:

with cte as (
    select 
        t1.table_1_id, 
        array_agg(t2.geom order by ordinality) table_2_geom
    from 
        table_1 t1
        cross join lateral unnest(t1.table_2_id_list) with ordinality i(table_2_id) 
        inner join table_2 t2 on t2.table_2_id = i.table_2_id
    group by t1.table_1_id
)
update table_1 t1
set table_2_geom = c.table_2_geom
from cte c
where c.table_1_id = t1.table_1_id

update后的DB Fiddle -table 內容演示

table_1_id | table_2_id_list | table_2_geom       
---------: | :-------------- | :------------------
         1 | {1,3,5}         | {geom1,geom3,geom5}
         2 | {2,4,6}         | {geom2,geom4,geom6}

但是相關子查詢可能更簡單:

update table_1 t1
set table_2_geom = (
    select array_agg(t2.geom order by ordinality)
    from unnest(t1.table_2_id_list) with ordinality i(table_2_id)
    inner join table_2 t2 on t2.table_2_id = i.table_2_id

)

DB Fiddle 上的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM