【问题标题】:Joining a PostgreSQL table into another table's column将 PostgreSQL 表连接到另一个表的列
【发布时间】:2018-08-09 10:10:32
【问题描述】:

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

例如,如果我有一个 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 还是很陌生,据我所知,这是徒劳的,甚至是不可能的,但如果是的话,我当然不知道该怎么做。

【问题讨论】:

    标签: sql postgresql massive


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      您可以通过将调用嵌套到 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;
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-22
        • 1970-01-01
        相关资源
        最近更新 更多