If we have two tables, people and groups, where people has a column group_ids which is an array of ids from groups, we can map the array of ids to the matching name from groups using the following query:
select
p.email as email,
coalesce(groups.names, '') as group_names
from people as p
inner join (
select string_agg(g.name, ', ') as names, person.id as person_id
from entity_groups as g
inner join (
select id, unnest(group_ids) as group_id
from people
) as person on person.group_id = g.id
group by person.id
) as groups on groups.person_id = p.id
order by email;
It is a three-step process, listed inside to out (i.e. the innermost query is executed first):
- Convert the
group_idsarray frompeopleinto a table ofperson_idandgroup_idusingunnest - Join the
group_idwith theidofgroupsto get thenameof the group - Aggregate the
nameof the groups into a comma-separated string usingstring_agg