2

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

例如,如果我有一个 person 表和一个 cars 表:

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 很陌生,据我所知,这是一场疯狂的追逐,甚至是不可能的,但如果是这样,我当然不知道该怎么做。

4

2 回答 2

1

如果我没看错,你有一个 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;
于 2018-08-08T23:21:37.437 回答
0

您可以通过嵌套调用来做到这一点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;
于 2018-08-09T00:04:18.143 回答