我有如下表结构的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' );
我需要以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": []
}
]
似乎我需要混合左加入和分组,但我不知道怎么做:
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"
1条答案
按热度按时间e4yzc0pl1#
你可以使用
json_agg
以及json_build_object
基于GROUP BY
条款。之后,您可以使用row_to_json
在子查询中,例如。看到了吗
db<>fiddle 1
或者db<>fiddle 2