【问题标题】:Possible recursive solution in MySQL to find comments and replies在 MySQL 中查找评论和回复的可能递归解决方案
【发布时间】: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


【解决方案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 加入它们,我必须创建一个新列 (new_id) 才能使用它进行排序,但是你有一个问题站立将是首先出现的评论,因此我建议您添加 created_on_date 列,以便将其用作第二个索引进行排序。

附:我花了将近一个小时才给你:D

【讨论】:

    猜你喜欢
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多