【问题标题】:Postgresql - Return a column resulting from join as single json columnPostgresql - 将连接产生的列作为单个 json 列返回
【发布时间】:2018-10-27 05:11:39
【问题描述】:

usersroles 表之间存在多对多关系(典型用例)。它们使用 user_role 表关联在一起。我执行以下查询:

select 
    u.id, u.first_name, u.last_name, u.middle_name,
    u.email_address, r.id, r.role_code
from 
master.user u
left join
master.user_role ur 
    on ur.user_id = u.id
    and ur.is_void = false
left join
master.role r
    on r.id = ur.role_id
    and r.is_void = false
where u.id = 7  and u.is_void = false

结果

7;"Multi Role";"First";"Middle";"mult@gmail.com";1;"ST"
7;"Multi Role";"First";"Middle";"mult@gmail.com";2;"TC"

我如何将角色聚合到一个 json 或数组列中,以使其结果:

7;"Multi Role";"First";"Middle";"mult@gmail.com";[{id: 1, role_code : ST}, {id: 2, role_code: TC}]

【问题讨论】:

  • 请修正您的示例:在您的查询中,“first_name”列中有“Multi Role”。我认为这是不正确的,不是吗?

标签: sql json postgresql join


【解决方案1】:

demo: db<>fiddle

SELECT 
    id, 
    first_name, 
    last_name, 
    middle_name, 
    email_address, 
    jsonb_agg(
        jsonb_build_object('id', r_id, 'role_code', role_code)
    )
FROM 
    result_table
GROUP BY id, first_name, last_name, middle_name, email_address
  1. jsonb_build_objectPostgres JSON functions创建一个json对象
  2. jsonb_aggPostgres aggregate functions聚合json对象

当然你也可以使用json 来代替jsonbPostgres JSON types

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-15
    • 2021-08-21
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 2016-10-05
    相关资源
    最近更新 更多