Skip to content
Advertisement

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

I am trying to unnest an array from one table using ORDINALITY to preserve order, then perform an INNER JOIN on another table to find the corresponding value from a specific column and then use ARRAY_AGG to package this back up and UPDATE the original table. I have something working for a single query, but I want to do an UPDATE on each row in a table but can’t seem to get it to work. I feel like I’m close but I’m spending too long on this so any help would be appreciated.

Code is below to generate the tables, alongside the answer I am looking for and my attempts.

I want to end up with this:

I can get it working for the single case using the following:

But when I try to do something similar to UPDATE each row in the table, I do something wrong. I’ve tried the following but it doesn’t work:

If anyone can point me in the correct direction I would be very grateful.

Thanks

Advertisement

Answer

You could turn your existing query to a CTE and join it back with the original table for update:

Demo on DB Fiddle – table content after the update:

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

But a correlated subquery might be simpler:

Demo on DB Fiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement