json 如何在Postgres查询中返回连接到单个属性的结果?

j9per5c4  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(146)

假设如下,

CREATE SCHEMA IF NOT EXISTS my_schema;

CREATE TABLE IF NOT EXISTS my_schema.my_table_a (
    id serial PRIMARY KEY
);

CREATE TABLE IF NOT EXISTS my_schema.my_table_b (
    id serial PRIMARY KEY,
    my_table_a_id BIGINT REFERENCES my_schema.my_table_a (id) NOT NULL
);

INSERT INTO my_schema.my_table_a VALUES
    (1);

INSERT INTO my_schema.my_table_b VALUES
    (1, 1),
    (2, 1),
    (3, 1);

如果运行以下查询,

SELECT
    ta.*,
    tb as tb
FROM my_schema.my_table_a ta
LEFT JOIN my_schema.my_table_b tb
    ON ta.id = tb.my_table_a_id;

那么结果就是,

[
    {
        "id": 1,
        "tb": {
            "id": 1,
            "my_table_a_id": 1
        }
    },
    {
        "id": 1,
        "tb": {
            "id": 2,
            "my_table_a_id": 1
        }
    },
    {
        "id": 1,
        "tb": {
            "id": 3,
            "my_table_a_id": 1
        }
    }
]

我怎样才能让它像这样工作:

[
    {
        "id": 1,
        "tb": [
            {
                "id": 1,
                "my_table_a_id": 1
            },
            {
                "id": 2,
                "my_table_a_id": 1
            },
            {
                "id": 3,
                "my_table_a_id": 1
            }
        ]
    }
]
jdzmm42g

jdzmm42g1#

SELECT
ta.*,
ARRAY_AGG(tb) AS tb
FROM my_schema.my_table_a ta, my_schema.my_table_b tb
GROUP BY ta.id
ORDER BY ta.id;

示例https://www.db-fiddle.com/f/5i97YZ6FMRY48pZaJ255EJ/0

相关问题