r/learnSQL • • 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

9 comments sorted by

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!

1

u/Dan6erbond Mar 26 '21

Ohhh... Every comment in the CTE can be joined with a parent comment until one is reached without a parent. This is so mind-blowing lol. I'm not really a database guy myself but building my own product so I had to get my hands dirty.

So far I had only seen Reddit use the post_id tactic, which seemed so wrong to me and finally it's starting to click! The linked list analogy makes a lot of sense. Appreciate you taking the time to explain this so detailed a ton!