如何连接表并以json的形式返回?

6uxekuva  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(276)

我有如下表结构的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"
e4yzc0pl

e4yzc0pl1#

你可以使用 json_agg 以及 json_build_object 基于 GROUP BY 条款。之后,您可以使用 row_to_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)

看到了吗 db<>fiddle 1 或者 db<>fiddle 2

相关问题