开发者

What is the most efficient way to pull parent and child items (ordered) from the same table in MySQL?

开发者 https://www.devze.com 2023-04-05 18:53 出处:网络
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 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 tree开发者_如何学编程s 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.


This should give you the first N posts and their comments in the order you wanted.

Select post_id,parent_id from table 
    where coalesce(parent_id, post_id) in (
        select post_id from table 
            where parent_id = '' 
            order by date desc limit N
        )
    order by coalesce(parent_id, post_id), parent_id desc, date desc;

Not sure if it is the most efficient way to do it though.

0

精彩评论

暂无评论...
验证码 换一张
取 消