Example: I have some articles and comments and I want to get something like this:
[{
title: "Article 1",
content: "Super long article goes here",
comments: [
{ author: "Troll", message: "You suck, Sir!" },
{ author: "SpamBot", message: "http://superawesomething.com/"}
]
},{
title: "Article 2",
content: "Another long article goes here",
comments: [ ... ]
}]
Right now I see two solutions:
IN condition and finally add the comments to the respective articles.articles.content will be transmitted for every comment - unless there is a way to do the join I am not aware of.I'm hoping that my SQL-illiteracy makes me miss the simple solution.
You can do this, using aggregates and/or subqueries. Something like:
select title, content, json_agg(comments.author, comments.message) as comments
from articles
join comments on articles.article_id = comments.article_id
group by article_id;
If you need this aggregated into one string/json/something - just wrap it into another aggregate query like this:
select json_agg(sub)
from (
select title, content, json_agg(comments.author, comments.message) as comments
from articles
join comments on articles.article_id = comments.article_id
group by article_id) sub;
This is a Postgres query. Have no expirience with Mysql.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With