我的Postgres数据库有一个返回JSON的SQL API。
我有两个表:holidays
,它的模式是name
,hd_id
。以及当天拍摄的照片。它的模式是photos
,url
,caption
。
我想创建一个嵌套的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
但这给了我一个错误
h_id
。照片是表,不是架构。我好像不像this seemingly related question犯同样的错误。我不知道该如何构造连接。这是所需的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'
}
]
}
]
最佳答案
group_concat
中没有PostgreSQL
。您可以使用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
参见本例中的
或者使用JSON functions。version 9.3中也有很好的JSON支持
关于sql - 来自Postgres API的嵌套JSON,架构不存在?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18537068/