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/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_idtactic, 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!