mysql - SQL 如何统计单个评论在多个级别上的所有回复

标签 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');

最佳答案

尝试以下查询:

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

关于mysql - SQL 如何统计单个评论在多个级别上的所有回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873946/

相关文章:

SQL Server 2008 R2存储过程多次执行时输出结果顺序不同

mysql - 如何检查记录不包含特定字符串?

mysql - 在CentOS 7.0上从源代码安装MySQL 5.6,但没有任何反应

php - 将唯一ID添加到php mysql上传

Java/JDBC/SQLite - 更新 BLOB 问题

mysql - 从 SELECT 中对 SQL 元组进行编号时获取 NULL 值

python - 将数据保存到数据库时出错

PHP 插入或更新表格

sql - 如何强制 MS Access 保留其 SQL 格式?

sql - 这段代码中的 IF 语句有什么问题?