微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql – 从SQL hasmany关系构造嵌套对象图

示例:我有一些文章评论,我想得到这样的东西:

[{
   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: [ ... ]
}]

现在我看到两个解决方案:

>首先获取文章,然后在具有一些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;

如果你需要将它聚合成一个字符串/ 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;

这是一个Postgres查询.没有MysqL的经验.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐