[英]How do I produce a JSON document from PostgreSQL 1:n tables?
I have the table "client" with:我有表“客户”:
id name registered_on status
-- ------- ------------- ------
1 Alice 2020-03-04 a
2 Vincent 2020-03-05 p
3 Anne 2020-03-06 a
And the table "account" with:和表“帐户”:
client_id account_number type balance
--------- -------------- ---- -------
1 300-1 CHK 100
2 307-5 SAV 24
2 307-6 CHK 350
I created them in DB Fiddle .我在DB Fiddle中创建了它们。
Now, I need a SQL query to produce the 1:n JSON document.现在,我需要一个 SQL 查询来生成 1:n JSON 文档。
There's a 1:n relationship between the tables and some clients may not have an account (such as "Anne"):表格之间存在 1:n 的关系,并且某些客户可能没有帐户(例如“Anne”):
[
{
"id":1,
"name":"Alice",
"registered_on":"2020-03-04",
"status":"a",
accounts: [
{
"account_number": "300-1",
"type": "CHK",
"balance": 100.00
}
]
},
{
"id":2,
"name":"Vincent",
"registered_on":"2020-03-05",
"status":"p",
accounts: [
{
"account_number": "307-5",
"type": "SAV",
"balance": 24
},
{
"account_number": "307-6",
"type": "CHK",
"balance": 350
}
]
},
{
"id":3,
"name":"Anne",
"registered_on":"2020-03-06",
"status":"a",
accounts: [ ]
}
]
The result is a simple join (probably an outer join) that I know how to do.结果是我知道该怎么做的简单连接(可能是外部连接)。 I just don't get how to produce a JSON document from it.
我只是不知道如何从中生成 JSON 文档。
I suppose the column id
of the client
table is a primary key.我想
client
表的列id
是主键。 The key functions to use are to_jsonb()
and jsonb_agg().
要使用的关键函数是
to_jsonb()
和jsonb_agg().
select jsonb_pretty(jsonb_agg(r))
from (
select
to_jsonb(c) || jsonb_build_object(
'accounts',
coalesce(nullif(jsonb_agg(to_jsonb(a)- 'client_id'), '[null]'), '[]')
) as r
from client c
left join account a on client_id = id
group by c.id
) s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.