Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL:选择评论和回复数量_Mysql - Fatal编程技术网

MySQL:选择评论和回复数量

MySQL:选择评论和回复数量,mysql,Mysql,我有一个“Comments”MySQL表,其中包含以下字段: 身份证 正文 父项id(默认为空) 基本上,我想选择所有具有空parent_id的注释,以及它们的回复总数。此评论系统只有一个级别的回复。结果将类似于: ------------------------------------------------- | id | Text | total_replies | ----------------------------------------

我有一个“Comments”MySQL表,其中包含以下字段:

  • 身份证
  • 正文
  • 父项id(默认为空)
基本上,我想选择所有具有空parent_id的注释,以及它们的回复总数。此评论系统只有一个级别的回复。结果将类似于:

-------------------------------------------------
| id | Text                     | total_replies |
-------------------------------------------------
| 1  | This is a comment        | 0             |
-------------------------------------------------
| 5  | another comment          | 3             |
-------------------------------------------------
| 7  | a different comment      | 1             |
-------------------------------------------------

感谢您的帮助:)

这可能是:

select c.id, c.Text, count(reply.id) as total_replies
from comments c 
left join comments reply on c.id = reply.parent_id
where c.parent_id is null
group by c.id

如果我正确理解注释和回复在同一个表中。

假设回复在同一个表中:

SELECT c1.id, c1.text, COUNT(c2.id) total_replies
FROM comments c1 
LEFT JOIN comments c2 ON c2.parent_id = c1.id
WHERE c1.parent_id IS NULL
GROUP BY c1.id, c1.text
ORDER BY c1.id

怎样才能
c1.parent\u id=c2.id
c1.parent\u id为NULL