MySQL中查找注释和回复的可能递归解决方案

MySQL中查找注释和回复的可能递归解决方案,mysql,Mysql,不是真正的(可能的)递归解决方案,但我已经多次遇到这个问题。我有一个名为post_comments的表,如下所示: Table: post_comments comment_id comment_text user_id parent_id type 1 'x' 1 15 1 2 'hi' 2 1

不是真正的(可能的)递归解决方案,但我已经多次遇到这个问题。我有一个名为post_comments的表,如下所示:

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'
获取(基本上,第一行是注释,下面是对注释的回复,这将一直持续到列出所有回复并且没有其他注释)

如何在一个查询中实现这一点?还是我的数据库结构有什么问题导致了这个问题?此外,最大嵌套可能为1(因为没有回复回复,只有回复评论)

这将起作用:

SELECT * FROM 
(SELECT comment_id as new_id,comment_text from `post_comments` WHERE `type` = 1) as parent
UNION ALL
SELECT * FROM 
(SELECT parent_id as new_id,comment_text from `post_comments` WHERE `type` = 2) as child
ORDER BY `new_id`
<>我基本上是把每个类型看作是一个单独的表,并根据一个普通的ID加入它们,我必须创建一个新的列(NeXyID)来使用它来进行排序,但是你有一个问题,那就是评论是先来的,因此,我建议您添加一个
created\u on\u date
列,以便将其用作第二个索引进行排序

p.S.我花了将近一个小时才为您弄到:D

这可能会有帮助:
comment_id   type
1             1
2             2
4             2
3             1
SELECT * FROM 
(SELECT comment_id as new_id,comment_text from `post_comments` WHERE `type` = 1) as parent
UNION ALL
SELECT * FROM 
(SELECT parent_id as new_id,comment_text from `post_comments` WHERE `type` = 2) as child
ORDER BY `new_id`