尝试获取结构如下的 JSON 响应:
{
'news_source_1' : [{'headline': 'title'},{'headline': 'title'}],
'news_source_2' : [{'headline': 'title'},{'headline': 'title'}],
'news_source_3' : [{'headline': 'title'},{'headline': 'title'}]
}
查询调用按 news_source 分组的单个表,news_source 是表中的一列。
我的代码按新闻来源分组但不使用新闻来源作为键:
SELECT array_to_json(array_agg(stories)) FROM stories GROUP BY source
返回:
{
[{'headline': 'title'},{'headline': 'title'}],
[{'headline': 'title'},{'headline': 'title'}],
[{'headline': 'title'},{'headline': 'title'}]
}
是否可以使用新闻来源列作为父键? 不确定如何使用 PG son 语法编写此 SQL 查询。
表格
stories (
news_source,
headline
)
最佳答案
不要聚合整行,只聚合标题:
SELECT json_build_object(news_source, json_agg(headline))
FROM stories
GROUP BY news_source
ORDER BY news_source;
关于json - Postgres 返回带组的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45157438/