I have a table of "posts" and "comments". Posts and comments have a post_id
, but comments also have a parent_id
that refers to another post in the same table.
I'm trying to find the most efficient way to pull the N most recent posts with their K most recent comments. The ordering I'm looking for is something like:
Post 1, Comment 1 (Parent 1), Comment 2 (Parent 1), .., Post 2, Comment 1 (Parent 2), Comment 2 (Parent 2), .... etc.
EDIT: My system is definitely only going to be a 2 level system (i.e. comments exist under posts, but it doesn't get any 'deeper'). I need high performance on both reads and writes but there will likely be about 5x-10x the number of reads as writes over a given interval. As such, I feel that a multi-table solution (i.e. separate tables for posts and comments) might result in higher than optimal cost for the reads. I've looked at the solution @BillKarwin linked to, which is great for trees or arbitrary depth but given that I know this constraint for my case I feel like there may be room to improve efficiency (maybe not!).
Thanks again to all who have responded, and thanks in advance to those who might.