I have been struggling writing this query. Say, I have mapping table and table with arrays of ids. I want to query for table with arrays of values:
id|value id_arr value_arr
--+----- --------- ---------
1| 4 {1, 2} -> {4, 5}
2| 5 {1, 3} {4, 7}
3| 7 {1, 2, 3} {4, 5, 7}
Anyone got idea on this one?
I'm using PostgreSQL, but I think it doesn't change much.
You can unnest the values and reaggregate:
select t2.*,
(select array_agg(t1.val)
from unnest(t2.arr) arr_val join
t1
on t1.id = arr_val
) as arr_ids
from t2 ;
If you want to preserve the original ordering, you can use with ordinality
:
select t2.*,
(select array_agg(t1.val order by n)
from unnest(t2.arr) with ordinality u(arr_val, n) join
t1
on t1.id = arr_val
) as arr_ids
from t2 ;
Here is a db<>fiddle.
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.