SQL如何在多个级别上计算单个注释的所有答复

时间:2018-10-18 12:23:21

标签: mysql sql

我正在研究评论系统,我必须在一个级别上统计一个评论的所有回复。

赞:

Parent
    ->child
        -> child

Parent
    -> child
    -> child
        ->child

我的Sql是:

CREATE TABLE IF NOT EXISTS `comment` (
  `id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'This is primary key of the table',  
  `parent_id` bigint(11) NOT NULL, 
  `content` text NOT NULL,
  PRIMARY KEY (`comment_id`),
  KEY `user_id` (`user_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=unicode_ci AUTO_INCREMENT=8 ;



INSERT INTO `comments` (`id`, parent_id`, `content`) VALUES
(1, 0, 'Parent'),
(2, 1, 'child'),
(3,  2, 'child'),
(4,  3, 'child'),
(5,  1, 'child2'),
(6, 0, 'Parent2'),
(7,  6,'child of parent2');

1 个答案:

答案 0 :(得分:0)

请尝试以下查询:

select count(*)
from comments c0
join comments c1 on c0.id = c1.parentid
-- in case if child comment doesn't have any children, we still need to keep it
left join comments c2 on c1.id = c2.parentid
where c0.id = 1 --particular id for which we want to count children