例如,我想知道子嵌套记录显示在父嵌套记录中的算法
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
如何编写查询来获得上述结果?
最佳答案
您可以使用如下所示的递归公用表表达式
;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
关于sql - SQL 嵌套注释背后的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693989/