r/learnSQL • u/Dan6erbond • Mar 25 '21
Modelling Data with Nested Comments - Retrieve Top Parent Post?
Hey everyone,
I feel like this is an issue almost every social media out there must have, Reddit, Twitter, etc. AFAIK Reddit seems to have parent_id in their model to do a simple SELECT * FROM posts WHERE id = comments.parent_id but I don't necessarily want to do that in my data model if it can be avoided.
Right now I use my code to recursively fetch parents until the parent is a post, and not a comment. But I'm wondering if MySQL or PostgreSQL have built-in features to retrieve an entry at the top-most level?
Appreciate the advice!
4
Upvotes
View all comments
Show parent comment
1
u/qwertydog123 Mar 26 '21
Not exactly, the JOIN statement in the CTE is what causes it to terminate. It will continue adding the parent row until 0 rows are returned from the join (e.g. when the parent_comment_id is NULL, or there is no matching id in the comments table). As soon as there are no rows returned then the CTE terminates. In this case it's similar to traversing a linked list.
The WHERE just filters the results from the CTE.
Hope that helps!