我有一个'Comments'MySQL表,其中包含以下字段:
基本上我想选择所有具有NULL parent_id的注释以及它们的回复总数。此评论系统只有一个级别的回复。结果看起来像:
-------------------------------------------------
| id | Text | total_replies |
-------------------------------------------------
| 1 | This is a comment | 0 |
-------------------------------------------------
| 5 | another comment | 3 |
-------------------------------------------------
| 7 | a different comment | 1 |
-------------------------------------------------
感谢您的帮助:)
答案 0 :(得分: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
如果我理解正确,评论和回复都在同一张表中。
答案 1 :(得分:0)
假设回复在同一张表中:
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