I got a self referencing table that's only 1 deep: comments and replies. A reply is just a comment with a parent id:
Comments (simplified):
- comment_id
- parentCommentId
Users have to scroll through the comments and replies and typically 10 new rows are being fetched each time, I'm trying out an recursive query for this:
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
obviously because of limit 10
not all the childs are being included this way and conversations will be cut off. What I actually want is a limit on the parents and have all childs included, regardless of how many total rows.
update
This is the actual query, now with limit in the first branch:
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
still, this doesn't give me the expected results, I get 1 comment as a result with no replies.
update 2
silly mistake on the where clause:
WHERE c.comment_id = ch.parent_comment_id
should've been
WHERE ch.comment_id = c.parent_comment_id
it's working now.