如果我以错误的方式接近/解释这个问题,请原谅我。
我有一张桌子,上面有关于我们在我们网站上发布的文章的信息。
我想做的是创建一个JSON对象,该对象按'sub_speciality_id'进行分类,并显示每篇最新的3篇文章。
所以基本上看起来像这样
每篇文章都有一个ID,news_type_id,标题和sub_speciality_id
所以本质上我想选择可以使用的不同sub_speciality_ids
/* selecting the sub_speciality ids where an article exists */
select DISTINCT(sub_speciality_id) from news_item where news_type_id = 1 AND sub_speciality_id is not null
然后针对每个要使用的sub_specialities生成类似JSON对象的
SELECT json_agg(row_to_json(r))
FROM
(select * from news_item where news_type_id = 1 AND sub_speciality_id =replace_me ORDER BY create_dt DESC LIMIT 3)r
但是用上面的ID替换'replace_me'
所以我想它看起来像(尽管我确定我在格式化时犯了一些错误):
{
"sub_specialities": {
"1": [
{
"id": 2328,
"news_type_id": 1,
"title": "This is a title",
"sub_speciality_id": 1
},{
"id": 2287,
"news_type_id": 1,
"title": "Blood Conservation Techniques",
"sub_speciality_id": 1
},{
"id": 2278,
"news_type_id": 1,
"title": "A Great Way to Do Apneic Oxygenation - Buccal O2",
"sub_speciality_id": 1
}],
"2": [
{
"id": 2328,
"news_type_id": 1,
"title": "This is a title",
"sub_speciality_id": 2
},{
"id": 2287,
"news_type_id": 1,
"title": "Blood Conservation Techniques",
"sub_speciality_id": 2
},{
"id": 2278,
"news_type_id": 1,
"title": "A Great Way to Do Apneic Oxygenation - Buccal O2",
"sub_speciality_id": 2
}],
"3": [
{
"id": 2328,
"news_type_id": 1,
"title": "This is a title",
"sub_speciality_id": 3
},{
"id": 2287,
"news_type_id": 1,
"title": "Blood Conservation Techniques",
"sub_speciality_id": 3
},{
"id": 2278,
"news_type_id": 1,
"title": "A Great Way to Do Apneic Oxygenation - Buccal O2",
"sub_speciality_id": 3
}]
}
}
答案 0 :(得分:1)
数据集:
CREATE TABLE t (sub_speciality_id INTEGER, news_type_id INTEGER, title TEXT, content TEXT);
INSERT INTO t
VALUES
(1, 1, 'a', 'some text a'),
(1, 2, 'b', 'some text b'),
(2, 1, 'c', 'some text c'),
(1, 1, 'd', 'some text d'),
(2, 2, 'e', 'some text e'),
(2, 1, 'f', 'some text f');
查询:
SELECT JSON_BUILD_OBJECT('sub_specialities', JSON_OBJECT_AGG(sub_speciality_id, item))
FROM (
SELECT sub_speciality_id, JSON_AGG(ROW_TO_JSON(t)) AS item
FROM t
WHERE news_type_id = 1
GROUP BY sub_speciality_id
) AS j
返回(美化后):
{
"sub_specialities": {
"1": [{
"sub_speciality_id": 1,
"news_type_id": 1,
"title": "a",
"content": "some text a"
}, {
"sub_speciality_id": 1,
"news_type_id": 1,
"title": "d",
"content": "some text d"
}],
"2": [{
"sub_speciality_id": 2,
"news_type_id": 1,
"title": "c",
"content": "some text c"
}, {
"sub_speciality_id": 2,
"news_type_id": 1,
"title": "f",
"content": "some text f"
}]
}
}