【问题标题】:how to obtain objects in objects (with all the key names) in SQL?如何在 SQL 中获取对象(具有所有键名)中的对象?
【发布时间】:2021-04-28 13:09:32
【问题描述】:

我的数据库包含两个名为 category 和 sport 的表:

category
-----------------------------------
id        |   title    | ...
1         |   summer
2         |   autumn
3         |   spring
4         |   winter

sport
--------------------------------------------------------------
id        |   title       | description | category_id  | ...
1         |   ski         | ...         |   4
2         |   surf        | ...         |   1
3         |   snorkeling  | ...         |   1
4         |   running     | ...         |   3
5         |   hiking      | ...         |   2
...

我的问题是如何通过 Sql (postgresql) 中的一个请求获得此结果:

{
        category: [
                {
                        c.id: 1,
                        c.title: summer,
                        sport: [
                                {
                                        s.id: 2,
                                        s.title: surf,
                                },
                                {
                                        s.id: 3,
                                        s.title: snorkeling,
                                },
                        ],     
                },
                {
                        c.id: 2,
                        c.title: autumn,
                        sport: [
                                {
                                        s.id: 5,
                                        s.title: hiking
                                }
                        ],
                },
                {
                        c.id: 3
                        c.title: spring,
                        sport: [
                                {
                                        s.id: 4,
                                        s.title: running,
                                }
                        ],
                },
                {
                        ...
                }               
        ]
}

我已尝试使用 ARRAY_AGG,但它删除了 key_names,我需要它在我的 API 中调用这些值。

【问题讨论】:

  • 你真的需要 JSON 还是想要一个普通的结果集

标签: sql node.js arrays json postgresql


【解决方案1】:

需要结合jsonb_agg(),to_jsonb()andjsonb_build_object()`

select to_jsonb(c)||jsonb_build_object('sport', jsonb_agg(to_jsonb(s) - 'category_id'))
from category c
  join sport s on s.category_id = c.id
group by c.id;

以上假设category.id被定义为主键。

每个类别返回一行。

如果你真的想要一个包含所有行的巨大数组,你需要分两步聚合:

select jsonb_build_object('category', jsonb_agg(to_jsonb(c)||sport))
from category c
   join (
    select category_id, jsonb_build_object('sport', jsonb_agg(to_jsonb(s) - 'category_id')) as sport
    from sport s
    group by s.category_id
  ) s on s.category_id = c.id

Online example

【讨论】:

  • 第二个解决方案是完美的!非常感谢!
猜你喜欢
  • 1970-01-01
  • 2018-04-14
  • 2020-12-14
  • 2020-09-11
  • 1970-01-01
  • 2021-05-20
  • 2019-05-01
  • 1970-01-01
  • 2011-05-22
相关资源
最近更新 更多