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
I think it's starting to make more sense lol but to be clear does that mean that the terminating statement is actually the
WHEREclause in the finalSELECTand not within theWITH RECURSIVECTE?From what I had been reading online I assumed that the CTE itself would need to be aware of the end of the recursion so I think that's what's still confusing me a bit.