【问题标题】:Nested JSON from Postgres API, schema does not exist?来自 Postgres API 的嵌套 JSON,模式不存在?
【发布时间】:2013-08-30 15:56:19
【问题描述】:

我有一个用于返回 JSON 的 Postgres 数据库的 SQL API。

我有两个表:holidays,其架构为namehd_id。还有photos,这是那天拍的照片。它的架构是urlcaptionh_id

我想创建一个嵌套的 json 对象,如下所示。我正在运行的 SQL 是

    SELECT holidays.name, holidays.h_id, 
    concat('[', group_concat(concat('{"src":"', photos.url, '","caption":"', photos.caption '"}', separater ','), ']') ) 
    FROM holidays 
    INNER JOIN photos 
    ON holidays.h_id = photos.h_id 
    GROUP BY holidays.h_id

但这给了我错误"schema "photos" does not exist"。照片是一个表,而不是一个模式。我似乎没有犯与this seemingly related question 相同的错误。我不确定如何构建 JOIN。

这是所需的 JSON 输出。

   [
    {
        name: 'Labor Day',
        h_id: 'a1',
        photos: [
            {
                src: 'url',
                caption: 'text'
            },
            {
                src: 'url',
                caption: 'text'
            }
        ]
    },
    {
        name: 'MLK Day',
        h_id: 'a2',
        photos: [
            {
                src: 'url',
                caption: 'text'
            },
            {
                src: 'url',
                caption: 'text'
            }
        ]
    }
   ]

【问题讨论】:

标签: sql json postgresql


【解决方案1】:

PostgreSQL 中没有 group_concat。你可以使用string_agg:

select
    h.name, h.h_id, 
    '[' || string_agg('{"src":"' || p.url || '", "caption":"' || p.caption  || '"}', ',') || ']'
from holidays as h
    inner join photos as p on h.h_id = p.h_id 
group by h.name, h.h_id

查看sql fiddle demo 这个例子

或使用JSON functionsversion 9.3 中也有很好的 JSON 支持

【讨论】:

  • 这行得通,谢谢!我最终在 string_agg 行(答案代码中的第三行)之后添加了“AS children”,以便返回的列有一个好听的名称。
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 2020-11-27
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 2016-03-22
  • 2015-01-27
相关资源
最近更新 更多