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