Dmi*_*kov 5 sql postgresql json
我的 PostgreSQL 具有以下表结构:
CREATE TABLE "objs"("number" Integer,"name" Text NOT NULL, "price" Text NOT NULL );
CREATE TABLE "users"("name" Text NOT NULL,"obj_number" Text NOT NULL );
INSERT INTO "objs" ("number","name","price") VALUES ( 1,'Small Red Apples','30' );
INSERT INTO "objs" ("number","name","price") VALUES ( 1,'Big Apples','50' );
INSERT INTO "objs" ("number","name","price") VALUES ( 2,'Small Bottle','24' );
INSERT INTO "objs" ("number","name","price") VALUES ( 2,'Big Bottle','60' );
INSERT INTO "objs" ("number","name","price") VALUES ( 1,'Small green Apples','45' );
INSERT INTO "users" ("name","obj_number") VALUES ( 'Mike','1' );
INSERT INTO "users" ("name","obj_number") VALUES ( 'Jow','2' );
INSERT INTO "users" ("name","obj_number") VALUES ( 'Piter','3' );
Run Code Online (Sandbox Code Playgroud)
我需要以 JSON 格式返回 SELECT 结果:
[
{
"id": "1",
"name": "Mike",
"objs":
[
{
"number": 1,
"name": "Small Red Apples",
"price": "30"
},
{
"number": 1,
"name": "Small green Apples",
"price": "45"
},
{
"number": 1,
"name": "Big Apples",
"price": "50"
}
]
},
{
"id": 2,
"name": "Jow",
"objs": [{
"number": 1,
"name": "Small Bottle",
"price": "50"
},
{
"number": 1,
"name": "Small Bottle",
"price": "24"
}
]
},
{
"id": 2,
"name": "Jow",
"objs": []
}
]
Run Code Online (Sandbox Code Playgroud)
看来我需要混合 LEFT JOIN 和 group by,但我不知道该怎么做:
SELECT
u."name",
u."obj_number",
o."name",
o."price"
FROM "users" u
LEFT JOIN objs o ON u.obj_number = o."number"
-- GROUP BY u."name"
Run Code Online (Sandbox Code Playgroud)
json_agg您可以使用和的组合json_build_object来基于该GROUP BY子句构建 json 数组。之后,您可以row_to_json在子查询中使用将所有行转换为 json 文档,例如
SELECT row_to_json(j) FROM (
SELECT
u.name,
u.obj_number,
json_agg(json_build_object('name', o.name, 'price', o.price)) AS objs
FROM users u
LEFT JOIN objs o ON u.obj_number = o.number::text
GROUP BY u.name,u.obj_number) j;
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{"name":"Piter","obj_number":"3","objs":[{"name" : null, "price" : null}]}
{"name":"Jow","obj_number":"2","objs":[{"name" : "Small Bottle", "price" : "24"}, {"name" : "Big Bottle", "price" : "60"}]}
{"name":"Mike","obj_number":"1","objs":[{"name" : "Small Red Apples", "price" : "30"}, {"name" : "Big Apples", "price" : "50"}, {"name" : "Small green Apples", "price" : "45"}]}
(3 Zeilen)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2058 次 |
| 最近记录: |