Forgive me if I'm approaching / explaining this in the wrong manner.
I have a table which is filled with information about articles we post on our site.
What I would like to do is create a JSON object which categorises by the 'sub_speciality_id' and shows the 3 most recent articles for each.
so essentially it looks like this
for each article we have an id, news_type_id, title and sub_speciality_id
So essentially I want to SELECT the different sub_speciality_ids which I can do with
/* 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
Then for each of the sub_specialities I want to use that to produce a JSON object much like
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
BUT replacing 'replace_me' with the ID above for each
So I guess it would look something like (although I'm sure I've made some errors in formatting that):
{
"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
}]
}
}