簡體   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