简体   繁体   English

使用多个值Postgres更新列

[英]Update column with multiple values Postgres

Sample data: 样本数据:

样本数据

I am trying update a column with values from multiple columns in another table if two columns match. 如果两列匹配,我尝试使用另一个表中多个列的值更新列。

Consider the following query: 考虑以下查询:

UPDATE application_table
SET    asset_list = asset_table.asset_name
FROM   asset_table
WHERE  application_table.application_name = asset_table.applications;

My table structure is: 我的表结构是:

application_table:
"asset_list";         "text[]"
"application_name";   "character varying"

asset_table:
"asset_name";         "character varying"
"applications";       "character varying"

I get the following error: 我收到以下错误:

ERROR:  column "asset_list" is of type text[] but expression is of type character varying
Line 12 SET    asset_list = asset_table.asset_name

What you need to do is aggregate the asset_name per applications value and set asset_list to that aggregated value. 您需要做的是汇总每个applicationsasset_name值,并将asset_list设置asset_list汇总值。

Problem is you can't do something like 问题是你不能做这样的事情

UPDATE ..
SET asset_list = ARRAY_AGG(asset_name)
FROM ...

because aggregate functions are not allowed in updates like that. 因为在这样的更新中不允许使用聚合函数。

So here's two other ways to do it: 所以这是另外两种方法:

UPDATE app_table
SET asset_list = _asset_list
FROM (
    SELECT applications, ARRAY_AGG(asset_name ORDER BY asset_name) AS _asset_list
    FROM asset_table
    GROUP BY applications
) AS a
WHERE app_name = applications;

https://www.db-fiddle.com/f/pKB5k6Lexwzqv6ZbCCdJay/0 https://www.db-fiddle.com/f/pKB5k6Lexwzqv6ZbCCdJay/0

This first builds a result set of distinct application names and an array of all the asset_name s for each of the app names. 首先,这将构建一个包含不同应用程序名称的结果集,并为每个应用程序名称构建一个包含所有asset_name的数组。 Then it updates the table as usual with that array value. 然后,它将照常使用该数组值更新表。

Another way is: 另一种方法是:

UPDATE app_table
SET asset_list = (SELECT ARRAY_AGG(asset_name ORDER BY asset_name)
                  FROM asset_table
                  WHERE applications = app_name)
;

https://www.db-fiddle.com/f/8oVWsubXW93n142gtZYLXB/0 https://www.db-fiddle.com/f/8oVWsubXW93n142gtZYLXB/0

This will update every record in app_table, and calculates the array value on the fly for every record. 这将更新app_table中的每条记录,并为每条记录动态计算数组值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM