在postgres select中,将列子查询返回为数组?

cc *_*ung 9 arrays postgresql subquery aggregate-functions

(以前做过这个,但是内存消失了,就像护目镜一样)

希望得到从选择userstag.tag_id为每个用户返回一个数组S.

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就是一个数组

kli*_*lin 15

使用聚合函数:

select
    usr_id, 
    name, 
    array_agg(tag_id) as tag_arr
from users
join tags using(usr_id)
group by usr_id, name
Run Code Online (Sandbox Code Playgroud)

或子查询结果中的数组构造函数:

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
Run Code Online (Sandbox Code Playgroud)

第二个选项简单快速,而第一个选项更通用,例如,当您需要使用多个聚合时.


Ali*_*jad 7

使用arrayPostgreSQL的构造函数:

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;
Run Code Online (Sandbox Code Playgroud)

笔记:

If you're using psycopg2 with python, then the result will be converted to a python list as well! (Although for uuid[] array, you will need to convert it to text[] array using array(...)::text[], if you want to get IDs in python list). See this for details.