将 PostgreSQL table 加入另一个 table 的列

Joining a PostgreSQL table into another table's column

我正在寻找一种方法将两个 table 连接在一起,但不是以匹配外键和创建匹配行的传统方式。

比如我有一个人table和一辆车table:

Table person
| name | age | cars |
| ---- | --- | ---- |
| Mike | 41  |  {}  |

Table cars
| owner | make | model | year |
| ----- | ---- | ----- | ---- |
| Mike  | Honda| Civic | 2012 |
| Mike  | Ford | Focus | 2018 |

是否可以查询如下所示的结果:

{
    name: 'Mike',
    age: 41,
    cars: [{
        make: 'Honda',
        model: 'Civic',
        year: 2012
    },
    {
        make: 'Ford',
        model: 'Focus',
        year: 2018
    }]
}

我正在使用 node/express/massive 如果这有影响的话。我是 SQL 的新手,据我所知,这是一场徒劳的追逐,甚至是不可能的,但如果是这样,我当然不知道怎么做。

如果我没看错的话,你有一个 json 对象数组。我觉得很好奇,但你可以在 Postgres 中构建它:

select p.name, p.age,
       array_agg(json_build_object('car', car, 'model', model, 'year', year)) as info
from person p join
     cars c
     on p.name = c.owner
group by p.name, p.age;

您可以通过嵌套调用 json_build_object():

来实现
select json_build_object(
        'name', p.name,
        'age', p.age,
        'cars': array_agg(json_build_object('car', car, 'model', model, 'year', year)) 
    ) as info
from person p left join
     cars c
     on p.name = c.owner
group by p.name, p.age;