PostgreSQL 获取有限制的嵌套行

PostgreSQL get nested rows with limit

我得到了一个自引用 table,它只有 1 个深度:评论和回复。回复只是带有 parent id:

的评论
Comments (simplified):
    - comment_id
    - parentCommentId

用户必须滚动浏览评论和回复,通常每次都会获取 10 行新行,我正在为此尝试递归查询:

WITH RECURSIVE included_childs(comment_id, parent_comment_id) AS 
    (SELECT comment_id, parent_comment_id
    FROM comments 
  UNION 
    SELECT c.comment_id, c.parent_comment_id
    FROM included_childs ch, comments c
    WHERE c.comment_id = ch.parent_comment_id
  )
SELECT *
FROM included_childs
limit 10

显然是因为 limit 10 并非所有孩子都以这种方式包含在内,对话将被切断。我真正想要的是限制 parent 并包含所有子项,无论总行数如何。

更新

这是实际查询,现在在第一个分支中有限制:

WITH RECURSIVE included_childs(comment_id, from_user_id, fk_topic_id, comment_text, parent_comment_id, created) AS 
    ((SELECT comment_id, from_user_id, fk_topic_id, comment_text, parent_comment_id, created 
    FROM vw_comments WHERE fk_topic_id = 2
    and parent_comment_id is null
    limit 1)
  union all 
    SELECT c.comment_id, c.from_user_id, c.fk_topic_id, c.comment_text, c.parent_comment_id, c.created
    FROM included_childs ch, vw_comments c
    WHERE c.comment_id = ch.parent_comment_id
  )
SELECT *
FROM included_childs

不过,这并没有给我预期的结果,结果我收到了 1 条评论,但没有回复。

更新 2

where 子句上的愚蠢错误:

WHERE c.comment_id = ch.parent_comment_id

应该是

WHERE ch.comment_id = c.parent_comment_id

现在可以使用了。

我认为递归 CTE UNION 中的第一个分支应该是这样的:

SELECT comment_id, parent_comment_id
FROM comments
WHERE parent_comment_id IS NULL
LIMIT 10

然后您将获得这 10 "root" 条评论的所有回复。 我希望那里有某种 ORDER BY,除非您不关心顺序。

UNION ALL 会比 UNION 更糟,而且不可能有循环,对吗?