[英]How do I update a column to be a list of values from another table using Postgresql?
sorry I'm quite new to SQL so I'm having trouble finding out how to write the queries.抱歉,我对 SQL 很陌生,所以我很难找出如何编写查询。 Let me explain what's happening:
让我解释一下发生了什么:
In Postgres , I have table_a with a column of "account_name", and a column to be calculated based on another table, table_b;在Postgres中,我有一个 table_a,其中有一列“account_name”,还有一个要根据另一个表 table_b 计算的列; we'll call this calculated column "column_a" to match the title of this question.
我们将此计算列称为“column_a”以匹配此问题的标题。 table_b has a column that should match the values of the "account_name" column, or not.
table_b 有一列应该与“account_name”列的值匹配,或者不匹配。 table_b also has a column with "name".
table_b 也有一列带有“名称”。
I want to populate table_a's "column_a" with a list of "name"'s from table_b where "account_name" of table_b equals the "account_name" value from table_a whenever table_b is updated or a new row is inserted.我想用 table_b 中的“名称”列表填充 table_a 的“column_a”,其中每当更新 table_b 或插入新行时,table_b 的“account_name”等于 table_a 的“account_name”值。
table_a:表_a:
column_a ![]() |
account_name![]() |
---|---|
null ![]() |
Worker![]() |
null ![]() |
Boss![]() |
table_b:表_b:
name![]() |
account_name![]() |
---|---|
Bob![]() |
Worker![]() |
Alice![]() |
Boss![]() |
Tom![]() |
Worker![]() |
Brad![]() |
Investor![]() |
Once populated, table_a should look like this:填充后,table_a 应如下所示:
column_a ![]() |
account_name![]() |
---|---|
Bob,Tom![]() |
Worker![]() |
Alice![]() |
Boss![]() |
I know I have to create a trigger to run a function whenever table_b is updated or had a row inserted, and I also have to define this function.我知道每当 table_b 更新或插入一行时,我必须创建一个触发器来运行 function,而且我还必须定义这个 function。
However, I'm quite new to SQL and looking at similar questions to this is really hard for me to find what's applicable or convertible to my situation.但是,我对 SQL 还是很陌生,并且查看与此类似的问题对我来说真的很难找到适用或可转换为我的情况的内容。 So once I figure this out, other things should come a bit easier for me.
因此,一旦我弄清楚了这一点,其他事情对我来说应该会容易一些。 Would really appreciate someone helping me out and explaining why for as much as you can.
非常感谢有人帮助我并尽可能多地解释原因。
Thanks so much!非常感谢!
Aggregation function string_agg is a subselet, will return only 1 value, whih you can use to update聚合 function string_agg 是一个子集,只会返回 1 个值,您可以使用它来更新
UPDATE tablea ta SET "column_a" = (SELECT string_agg("name",',') FROM tableb WHERE "account_name" = ta."account_name")
2 rows affected2 行受影响
SELECT * FROM tablea
column_a |列_a | account_name:------- |:----------- Bob,Tom |
account_name:------- |:------------ Bob,Tom | Worker Alice |
工人爱丽丝 | Boss
老板
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.