Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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` bigint(10) unsigned not null auto_increment,
    `parent_id` bigint(10) unsigned default 0,
    `date_sent` datetime not null,
    `content` text not null,
    PRIMARY KEY(`id`)
) ENGINE=InnoDB;

I'd like to select parent rows, and the children of those rows. I don't allow children to have children, so it's just one parent, with any number of children.

I think I've seen this done with unions before, or inner joins.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
501 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...