postgresql 需要通过数组连接更新Postgres表中的行

pkln4tw6  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(139)

我的表模式看起来是这样的:

create table table_with_arrays
(
    dim_col_code_array integer[] -- contains foreign keys to dict_table.array_code
    dim_col_val_array  varchar[] -- needs to be populated with dict_table.array_value
);

create table dict_table(
   array_code integer,
   array_value varchar
)

字符串
有一个字段dim_col_code_array,其值为[10,300,400]。这些整数是dict_table.array_code的外键。
对于table_with_arrays的每一行,我需要通过dim_col_code_array = integer.array_code的每个元素将dim_col_code_array的每个值与表dict_table连接,然后将连接的array_value以相同的顺序存储到table_with_arrays.dim_col_val_array
范例:

table_with_arrays contains record:
[1,2,3], [/** fill me with values*/]

dict_table contains records
1 FIRST
2 SECOND
3 THIRD

query should update record of table_with_arrays to
[1,2,3], [FIRST, SECOND, THIRD]


有什么“聪明”的想法/见解我可以尝试吗?

wydwbb8l

wydwbb8l1#

连接可以使用操作符ANY来完成:

SELECT dim_col_code_array, array_agg(array_value ORDER BY array_code) as dim_col_val_array  
FROM table_with_arrays t
JOIN dict_table d ON d.array_code = ANY(t.dim_col_code_array)
GROUP BY dim_col_code_array

字符串
更新可以是:

UPDATE table_with_arrays t
SET dim_col_val_array = sub_q.dim_col_val_array 
FROM 
    (
    SELECT dim_col_code_array, array_agg(array_value ORDER BY array_code) as dim_col_val_array  
    FROM table_with_arrays t
    JOIN dict_table d ON d.array_code = ANY(t.dim_col_code_array)
    GROUP BY dim_col_code_array
    ) AS sub_q
WHERE sub_q.dim_col_code_array = t.dim_col_code_array;


Demo here

doinxwow

doinxwow2#

解嵌套数组WITH ORDINALITY以记住数组元素的原始顺序。
然后连接到查找表并将有序结果提供给ARRAY构造函数。
可以在相关子查询中完成:

UPDATE table_with_arrays t
SET   dim_col_val_array = ARRAY(
                           SELECT array_value
                           FROM   unnest(t.dim_col_code_array) WITH ORDINALITY AS a(array_code, ord)
                           JOIN   dict_table d USING (array_code)
                           ORDER  BY a.ord
                           );

字符串
fiddle
参见:

相关问题