在 postgres 选择中,将列子查询作为数组返回? [英] in postgres select, return a column subquery as an array?

查看:23
本文介绍了在 postgres 选择中,将列子查询作为数组返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(以前也这样做过,但是记忆会消失,就像护目镜一样)

希望从 users 中选择每个用户的 tag.tag_ids 作为数组返回.

<上一页>选择 usr_id,名称,(从标签 t 中选择 t.tag_id,其中 t.usr_id = u.usr_id)作为 tag_arr来自用户 u;

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

解决方案

使用 聚合函数:

选择usr_id,名称,array_agg(tag_id) 作为 tag_arr来自用户使用(usr_id)加入标签按 usr_id、名称分组

数组构造函数 来自子查询的结果:

选择u.usr_id,名称,大批(选择 tag_id从标签 t其中 t.usr_id = u.usr_id) 作为 tag_arr来自用户

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

注意,为了更好的性能,两个表中的 usr_id 列都应该被索引.虽然通常 users.usr_id 是主键,但有时可能会忘记引用列的索引也很有用.

(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.

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

with the idea embedded query tag_arr would be an array

解决方案

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 a simple one-source query while the first one is more generic, especially convenient when you need more than one aggregate from a related table. Also, the first variant should be faster on larger tables.

Note, that for better performance the usr_id columns in both tables should be indexed. While typically users.usr_id is a primary key, sometimes one may forget that the index of referencing column is also useful.

这篇关于在 postgres 选择中,将列子查询作为数组返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆