我得到了一个只有1层深度的自引用表:评论和答复。回复只是带有父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
导致并非所有孩子都被这样包含,并且对话将被切断。我真正想要的是对父母的限制,并且包括所有孩子,而不管总数有多少。
更新
这是实际的查询,现在在第一个分支中有限制:
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
现在正在工作。
答案 0 :(得分:1)
我认为递归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
溃烂,而且不可能有循环,对吧?