gpt4 book ai didi

mysql - 森林中的树结构。如何通过森林ID检索树?

转载 作者:行者123 更新时间:2023-11-29 08:23:20 25 4
gpt4 key购买 nike

问题本身可能写错了,所以如果有人有更好的想法如何定义它,请编辑问题。

<小时/>

结构

仅重要列。

评论

  • comment_id
  • comment_parent_id
  • 用户 ID
  • comment_text

帖子

  • post_id
  • 用户 ID
  • post_text

comments_to_post(comments_to_foos、comments_to_bars、...)

  • comment_id
  • post_id(foo_id、bar_id、...)
<小时/>

comments_to_post 仅与 comments 上的 comment_parent_idNULL 的评论有联系,因为所有其他评论都只是另一个评论的子项。

<小时/>

我正在努力处理查询,该查询在结果中会给我分配给特定帖子(按 post_id)及其子帖子的评论。

我尝试从 comments 中进行选择并加入 comments_to_post 其中 post_id = ? 但难怪我只得到了 NULL< 的评论 comment_parent_id 因为只有它们通过 comments_to_post 连接。

如何将那些子评论添加到结果中?

<小时/>

示例数据:

评论

comment_id comment_parent_id
1 NULL
2 1
3 1
4 NULL
5 4

帖子

post_id
10
20

对帖子的评论

comment_id post_id
1 10
4 20

预期结果

... where post_id = 10

comment_id
1
2
3

最佳答案

您应该将字段 post_id 添加到表 comments(在这种情况下,您不需要表 comments_to_posts)。只有在这种情况下,您才能通过一个数据库请求选择所有评论和子评论。

此外,如果您想在树结构中获得一些数据(评论、菜单等),我建议您阅读 http://en.wikipedia.org/wiki/Nested_set_model 。这是解决这个问题的一个非常有趣和优雅的方法。

关于mysql - 森林中的树结构。如何通过森林ID检索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18688196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com