假设如下,
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
}
]
}
]
1条答案
按热度按时间jdzmm42g1#
示例https://www.db-fiddle.com/f/5i97YZ6FMRY48pZaJ255EJ/0