How would one 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 would like the query to return a result lat looks something like this:
[
{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"
]},
]}
]
I know one can achieve this by 3 separate select queries in nested for loops. What I want to know is could this be achieved by one single postgres query?
Note: I am not good with PostgreSQL. Probably made wrong assumptions and code is probably not intended for production.
I almost sure you cannot just result a nested object. But you can receive JSON. So
SELECT json_build_object( 'school_name', school_name, 'people', ( SELECT json_agg(json_build_object( 'profile_name', profile_name, 'articles', ( SELECT json_agg(json_build_object( 'article_name', article_name )) FROM tb_article WHERE profile_id = tb_profile.facid ) )) FROM tb_profile WHERE school_id = tb_school.id ) ) AS result FROM tb_school
it will give you row as JSON, which you can JSON.parse
.
If you want to test you can use this learning service . I used it with this code.
SELECT json_build_object( 'name', firstname, 'slots', ( SELECT json_agg(json_build_object( 'number', slots, 'facility', ( SELECT json_agg(json_build_object( 'name', name )) FROM cd.facilities WHERE facid = cd.bookings.facid ) )) FROM cd.bookings WHERE memid = cd.members.memid ) ) AS result FROM cd.members
It probably will be helpful or provide more ideas.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.