Is it possible to create a multidimensional array from a single Postgres Query?
I have 3 tables with the following columns:
tb_school (id, school_name) eg:
[ {id:"1", school_name:"School1"}, {id:"2", school_name:"School2"} ]
tb_profile (id, profile_name, school_id) eg:
[ {id:"1", profile_name:"John", school_id:"1"}, {id:"2", profile_name:"Peter", school_id:"1"}, {id:"3", profile_name:"Sam", school_id:"1"}, {id:"4", profile_name:"Susan", school_id:"2"}, {id:"5", profile_name:"Jude", school_id:"2"}, {id:"6", profile_name:"Kim", school_id:"2"} ]
tb_article (id, article_name, profile_id) eg:
[ {id:"1", article_name:"Headline News", profile_id:"1"}, {id:"2", article_name:"Sports Recap", profile_id:"2"}, {id:"3", article_name:"Weather", profile_id:"3"}, {id:"4", article_name:"Arts", profile_id:"4"}, {id:"5", article_name:"Other", profile_id:"5"}, {id:"6", article_name:"Example", profile_id:"6"} ]
I am looking for the query result in this format:
[
{school_name:"School1", people:[
{profile_name:"John", articles:[
article_name:"Headline News"
]},
{profile_name:"Peter", articles:[
article_name:"Sports Recap"
]},
{profile_name:"Sam", articles:[
article_name:"Weather"
]},
]},
{school_name:"School2", people:[
{profile_name:"Susan", articles:[
article_name:"Arts"
]},
{profile_name:"Jude", articles:[
article_name:"Other"
]},
{profile_name:"Kim", articles:[
article_name:"Example"
]},
]}
]
Instead of using nested for loops and separate select queries, is there a way to achieve this with just one postgres query?