计算多个表

时间:2017-01-14 22:08:57

标签: sql-server tsql

我正在编写类似于博客的系统,其中帖子可以包含任意数量的评论。计算帖子顶级评论的数量是微不足道的,但问题是每个评论都可以有子评论。我不确定如何获得顶级评论和所有儿童评论的总数。我怎么能这样做呢?

为简单起见,所有帖子都只有一个ID,所有评论都只有一个帖子ID或一个父评论ID。

发表:

Id

注释:

Id
PostId
ParentCommentId

评论数据示例。带有PostId的行直接在帖子本身上发表评论:顶级评论。 ParentCommentId的评论会回复其他评论。

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

这将是上述帖子/评论的布局:

POST 1:
--comment 1
  --comment 2
    --comment 3
    --comment 4
--comment 5

POST 2:
--comment 6
  --comment 8
  --comment 9
--comment 7

查询帖子ID 1应返回5,帖子ID 2应返回4.

2 个答案:

答案 0 :(得分:1)

有没有?

-- Sample data.
declare @Samples as Table ( Id Int Identity, PostId Int, ParentCommentId Int );
insert into @Samples ( PostId, ParentCommentId ) values
  ( 1, NULL ), ( NULL, 1 ), ( NULL, 2 ), ( NULL, 2 ),
  ( 1, NULL ), ( 2, NULL ), ( 2, NULL ),
  ( NULL, 6 ), ( NULL, 6 );
select * from @Samples;

-- The query.
with Tree as (
  -- Top level comments.
  select Id, PostId
    from @Samples
    where PostId is not NULL -- You can specify a PostId here, e.g. "where PostId = 1".
  union all
  -- Children, one generation at a time.
  select S.Id, T.PostId
    from Tree as T inner join
      @Samples as S on S.ParentCommentId = T.Id
  )
  select PostId, Count( 42 ) as Comments
    from Tree
    group by PostId;

要查看中间结果,请将最终select替换为select * from Tree;

答案 1 :(得分:0)

我认为这个问题和答案会解决您的问题。 Simplest way to do a recursive self-join in SQL Server? 我有一个问题:在您的数据集中,您有两条PostID = 1且没有commentID的记录。它们不应该不同吗?

相关问题