Select Parent and Children With MySQL

后端 未结 3 1395
后悔当初
后悔当初 2020-12-16 18:05

I know this question comes up often, but today I can\'t find the answer I\'m looking for. I have a table with this schema.

CREATE TABLE `comments` (
    `id`         


        
3条回答
  •  半阙折子戏
    2020-12-16 18:39

    Parents are records with no parent_id.
    Children have parent_id equal to the parent comment's id.

      SELECT ...
        FROM comments AS parent
             LEFT JOIN comments AS child 
             ON child.parent_id = parent.id
       WHERE parent.parent_id IS NULL
    ORDER BY parent.id, child.id;
    

    Note that the self-join should be an outer join so that you don't miss parent comments with no children.

提交回复
热议问题