I'm writing a system similar to a blog, where a post can have any number of comments. Counting the number of top-level comments on a post is trivial, but the problem is that each comment can have child comments. I'm not sure how to get the total number of both the top-level comments and all child comments under them. How can I go about this?
For simplicity, all posts have only an ID and all comments will have exactly one of either a post ID or a parent comment ID.
Post:
Id
Comment:
Id
PostId
ParentCommentId
Example comment data. The rows with a PostId are comments directly on the post itself: top-level comments. The ones with a ParentCommentId are replies to other comments.
Id | PostId | ParentCommentId
---|--------|----------------
1  |   1    | NULL
2  |  NULL  | 1
3  |  NULL  | 2
4  |  NULL  | 2
5  |   1    | NULL
6  |   2    | NULL
7  |   2    | NULL
8  |  NULL  | 6
9  |  NULL  | 6
This would be the layout of the above posts/comments:
POST 1:
--comment 1
  --comment 2
    --comment 3
    --comment 4
--comment 5
POST 2:
--comment 6
  --comment 8
  --comment 9
--comment 7
Querying post ID 1 should return 5, and post ID 2 should return 4.
 
     
     
    