繁体   English   中英

如何组合两个表以在 postgresql 中获取 json 数组?

[英]How can I combine two tables to get json array in postgresql?

我在 postgresql 有两张桌子

表 A

id | name | b_codes
---|------|---------
1  | abc  | a,b
2  | def  | null

表 B

code | name
-----|------
a    | xx
b    | yy

我怎样才能得到这些(重点是 json 阵列):

查询 A.id=1:

{id: 1, name:'abc', b_codes:[{code: 'a', name: 'xx'}, {code: 'b', name: 'yy'}]}

查询 A.id=2:

{id: 2, name:'def', b_codes:[]}

或全部:

 id | name | codes
 ---|------|----------------------------------------------------
 1  | abc  | [{code: 'a', name: 'xx'}, {code: 'b', name: 'yy'}]
 2  | def  | []

您首先需要规范化数据 model 才能正确加入代码列表:

select a.id, a.name, x.*
from table_a a
  left join lateral (
    select b.code, b.name
    from unnest(string_to_array(a.b_codes, ',')) as c(code)
       join table_b b on b.code = c.code
  ) as x on true
; 

这将返回以下结果:

id | name | code | name
---+------+------+-----
 1 | abc  | a    | xx  
 1 | abc  | b    | yy  
 2 | def  |      |     

代码可以直接聚合到派生表中(子查询):

select a.id, a.name, coalesce(x.codes, '[]') as codes
from table_a a
  left join lateral (
    select jsonb_agg(jsonb_build_object('code', b.code, 'name', b.name)) as codes
    from unnest(string_to_array(a.b_codes, ',')) as c(code)
       join table_b b on b.code = c.code
  ) as x on true
;  

coalesce()是获取 id = 2 的空数组所必需的,否则派生表中的列codes将为 null。

现在可以将其转换为 JSON 值:

select jsonb_build_object('id', a.id, 'name', a.name, 'b_codes', coalesce(x.codes, '[]'))
from table_a a
  left join lateral (
    select jsonb_agg(jsonb_build_object('code', b.code, 'name', b.name)) as codes
    from unnest(string_to_array(a.b_codes, ',')) as c(code)
       join table_b b on b.code = c.code
  ) as x on true
;  

在线示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM