sorry I'm quite new to SQL so I'm having trouble finding out how to write the queries. 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; we'll call this calculated column "column_a" to match the title of this question. table_b has a column that should match the values of the "account_name" column, or not. table_b also has a column with "name".
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_a:
column_a | account_name |
---|---|
null | Worker |
null | Boss |
table_b:
name | account_name |
---|---|
Bob | Worker |
Alice | Boss |
Tom | Worker |
Brad | Investor |
Once populated, table_a should look like this:
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.
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. 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
UPDATE tablea ta SET "column_a" = (SELECT string_agg("name",',') FROM tableb WHERE "account_name" = ta."account_name")
2 rows affected
SELECT * FROM tablea
column_a | account_name:------- |:----------- Bob,Tom | Worker Alice | Boss
db<>fiddle here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.