in postgres select, return a column subquery as an array?

后端 未结 1 1698
挽巷
挽巷 2021-02-05 02:28

(have done this before, but memory fades, as does goggle)

wish to get select from users with the tag.tag_ids for each user returned as an array

相关标签:
1条回答
  • 2021-02-05 02:39

    Use the aggregate function:

    select
        usr_id, 
        name, 
        array_agg(tag_id) as tag_arr
    from users
    join tags using(usr_id)
    group by usr_id, name
    

    or an array constructor from the results of a subquery:

    select
        u.usr_id, 
        name, 
        array(
            select tag_id 
            from tags t 
            where t.usr_id = u.usr_id
            ) as tag_arr
    from users u
    

    The second option is simple and fast while the first one is more generic, especially convenient when you need more than one aggregate from a related table.

    0 讨论(0)
提交回复
热议问题