【问题标题】:Query for a threaded discussion查询线程讨论
【发布时间】:2011-08-07 19:43:31
【问题描述】:

我有一个带有自我引用 InReplyTo 的表,其中包含如下数据:

PostID InReplyTo Depth
------ --------- -----
1      null      0
2      1         1
3      1         1
4      2         2
5      3         2
6      4         3
7      1         1
8      5         3
9      2         2

我想编写一个查询,它将以线程形式返回此数据,以便 ID=2 的帖子及其所有后代将在 PostID=3 之前输出,以此类推以无限深度

PostID InReplyTo Depth
------ --------- -----
1      null      0
2      1         1
4      2         2
6      4         3
9      2         2
3      1         1
5      3         2
8      5         3
7      1         1

有没有简单的方法来实现这一点?我可以在这个阶段修改数据库结构,那么新的hierarchy 数据类型会是最简单的方法吗?或者可能是递归 CTE?

【问题讨论】:

    标签: sql-server-2008


    【解决方案1】:
    -- Test table
    declare @T table (PostID int, InReplyTo int, Depth int)
    
    insert into @T values  (1,  null, 0), (2,  1,  1), (3,  1,  1), (4,  2,  2), 
    (5,  3,  2), (6,  4,  3), (7,  1,  1), (8,  5,  3),(9,  2,  2)
    
    -- The post to get the hierarchy from
    declare @PostID int = 1
    
    -- Recursive cte that builds a string to use in order by
    ;with cte as
    (
      select T.PostID,
             T.InReplyTo,
             T.Depth,
             right('0000000000'+cast(T.PostID as varchar(max)), 10)+'/' as Sort
      from @T as T
      where T.PostID = @PostID
      union all
      select T.PostID,
             T.InReplyTo,
             T.Depth,
             C.Sort+right('0000000000'+cast(T.PostID as varchar(max)), 10)+'/'
      from @T as T
        inner join cte as C
          on T.InReplyTo = C.PostID
    )
    select PostID,
           InReplyTo,
           Depth,
           Sort
    from cte
    order by Sort
    

    结果:

    PostID      InReplyTo   Depth       Sort
    ----------- ----------- ----------- --------------------------------------------
    1           NULL        0           0000000001/
    2           1           1           0000000001/0000000002/
    4           2           2           0000000001/0000000002/0000000004/
    6           4           3           0000000001/0000000002/0000000004/0000000006/
    9           2           2           0000000001/0000000002/0000000009/
    3           1           1           0000000001/0000000003/
    5           3           2           0000000001/0000000003/0000000005/
    8           5           3           0000000001/0000000003/0000000005/0000000008/
    7           1           1           0000000001/0000000007/
    

    【讨论】:

      【解决方案2】:

      您正在寻找的确实是recursive query

      可以找到与您的案例匹配的示例here

      【讨论】:

      • 不完全是我要找的 - 我可以得到我需要的数据,但我想像问题中那样订购数据。因此,对于每个帖子,它会在以相同深度进入下一个帖子之前显示所有内容
      猜你喜欢
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2019-09-16
      • 2011-01-22
      • 2015-02-02
      • 1970-01-01
      相关资源
      最近更新 更多