一对多关系有两个表:
CREATE TABLE user (
id bigserial PRIMARY KEY,
name varchar(255) NOT NULL UNIQUE,
)
CREATE TABLE user_pets (
id bigserial PRIMARY KEY,
user_id int8 FOREIGN KEY REFERENCES user(id),
name varchar(255)
)
user.id
由DEFAULT
生成。
另一个包含用户及其宠物的json的表:
CREATE TABLE user_json (
user_id int8 FOREIGN KEY REFERENCES user(id),
full_info json
)
我希望我的json看起来像这样:
{
"id": 1,
"name": "John",
"pets": [
{
"id": 1,
"user": 1,
"name": "Kitty"
},
{
"id": 2,
"user": 1,
"name": "Cat"
}
]
}
我使用json_build_object
来处理用户,但我不知道如何将多行转换为宠物阵列:
json_build_object(
'id', user.id,
'name', user.name,
'pets', --WHAT SHALL I PASS HERE?
)
Postgres 10
答案 0 :(得分:2)
最后,这对我有用:
WITH all_pets AS (
SELECT *
FROM pets
WHERE pets.user_id = 1
)
INSERT INTO user_json (full_info)
SELECT
json_build_object(
'id', user.id,
'name', user.name,
'pets', (
SELECT json_agg(all_pets)
FROM pets
)
)
FROM user
WHERE user.id = 1;
答案 1 :(得分:0)
您可以使用json_to_recordset(),并使用CROSS JOIN LATERAL将其应用于您的json对象:
SELECT a.full_info->>'id', a.full_info->>'name', b.*
FROM user_json a
CROSS JOIN lateral json_to_recordset(a.full_info->'pets')
as b("id" integer
, "user" integer
, "name" varchar)