【发布时间】:2015-06-15 05:39:48
【问题描述】:
实际上(可能)不是递归解决方案,但我已经多次遇到这个问题。我有一个名为 post_cmets 的表,如下所示:
Table: post_comments
comment_id comment_text user_id parent_id type
1 'x' 1 15 1
2 'hi' 2 1 2
3 'yo' 5 15 1
4 'hey' 3 1 2
基本上,类型是TINYINT(1) 列。如果 type 为 2,则表示它是对评论的回复。如果 type 为 1,则它是对帖子的评论。像这样:
Post: 'texttexttextloremipsmu' by some uuser
Comments:
'x' <- Type 1
'yo' <- Type 2, reply to 'x'
如果type 为2,则表示parent_id 引用了表post_comments 中的某个comment_id。如果为 1,则它引用了帖子表 posts 中的帖子(未显示)。我需要一个 SQL 查询,它可以找到所有 cmets 并回复 post_id = 15 的帖子(即)。它需要返回类似UNION GROUP BY 的东西,其中伪代码是:
SELECT comment_id, type FROM post_comments WHERE parent_id = 15 and type = 1
UNION GROUP BY comment_id
SELECT comment_id FROM post_comments WHERE parent_id = comment_id
ORDER BY likes or date_posted (some arbitrary field)
获取(基本上第一行是评论,下面是评论的回复,直到列出所有回复并且没有其他 cmets)
comment_id type
1 1
2 2
4 2
3 1
如何在一个查询中完成此操作?还是我的数据库结构有问题导致此问题?最大嵌套可能是 1(因为没有回复,只有回复 cmets)
【问题讨论】:
标签: mysql