在 postgres select, return 中,列子查询作为数组?

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

(以前做过,但记忆力减退,护目镜也一样)

希望从 users 中获取 select,每个用户的 tag.tag_id 以数组形式返回。

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

嵌入式查询的想法 tag_arr 将是一个数组

使用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

或来自子查询结果的 array constructor

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

第二个选项是一个简单的单源查询,而第一个选项更通用,当您需要来自相关 table 的多个聚合时特别方便。此外,第一个变体在较大的 tables 上应该更快。

请注意,为了获得更好的性能,应该为两个 table 中的 usr_id 列编制索引。虽然通常 users.usr_id 是主键,但有时人们可能会忘记引用列的索引也很有用。

使用 PostgreSQL 的 array 构造函数:

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

注:

如果您将 psycopg2 与 python 一起使用,那么结果也将转换为 python list! (尽管对于 uuid[] 数组,如果您想在 python 列表中获取 ID,则需要使用 array(...)::text[] 将其转换为 text[] 数组)。有关详细信息,请参阅 this