SQL 嵌套评论背后的算法

Algorithm behind Nested comments with SQL

我想知道子嵌套记录背后的算法,例如显示在父嵌套记录中

Comment 1 (parent record)
reply 1 (child record)
reply 2 (child record)
reply 3 (child record)
view all

Comment 2 (parent record)
reply 1 (child record)
reply 2 (child record)
reply 3 (child record)
view all

如何编写查询以获得上述结果?

您可以使用如下所示的递归通用 Table 表达式

;WITH comments AS 
(
    SELECT 1 as ID,'Comment 1' detail,NULL AS ParentID
    UNION ALL SELECT 2 as ID,'Comment 2',NULL AS ParentID
    UNION ALL SELECT 3 as ID,'Reply 1',1 AS ParentID
    UNION ALL SELECT 4 as ID,'Reply 2',3 AS ParentID
    UNION ALL SELECT 5 as ID,'Reply 3',4 AS ParentID
    UNION ALL SELECT 6 as ID,'Reply 4',2 AS ParentID
    UNION ALL SELECT 7 as ID,'Reply 5',6 AS ParentID
),comment_hierarchy AS 
(
    SELECT ID,detail,ID AS prid,0 AS orderid
    FROM comments
    WHERE ParentID IS NULL
    UNION ALL 
    SELECT c.ID,c.detail ,ch.prid as prid,ch.orderid + 1
    FROM comments c
    INNER JOIN comment_hierarchy ch
    ON c.ParentID = ch.ID
)
SELECT ID,Detail
FROM comment_hierarchy
ORDER BY prid,orderid asc

更多信息请参考

https://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx

CTE to get all children (descendants) of a parent