SQL嵌套注释背后的算法

时间:2015-04-17 08:24:09

标签: sql sql-server recursive-query

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用递归公用表表达式,如下面的

;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