bac*_*dos 3 mysql sql postgresql
示例:我有一些articles,comments我希望得到这样的东西:
[{
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: [ ... ]
}]
Run Code Online (Sandbox Code Playgroud)
现在我看到两个解决方案:
IN条件的第二个查询中获取注释,最后将注释添加到相应的文章中.articles.content将被传输给每个评论 - 除非有一种方法可以进行连接我不知道.我希望我的SQL文盲能让我错过这个简单的解决方案.
您可以使用聚合和/或子查询来执行此操作.就像是:
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;
Run Code Online (Sandbox Code Playgroud)
如果你需要将它聚合成一个字符串/ json/something - 只需将它包装到另一个聚合查询中,如下所示:
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;
Run Code Online (Sandbox Code Playgroud)
这是一个Postgres查询.没有Mysql的经验.