sql - SQL 嵌套注释背后的算法

标签 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

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

最佳答案

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

;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

关于sql - SQL 嵌套注释背后的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29693989/

相关文章:

sql - 将具有小数点的 SQL Server 字符串拆分为多个列

mysql - SQL - 如何返回 0 的计数

SQL Server 2012 - 根据另一列的值重置运行总计

sql - 在 Sqlite 的以下查询中重用 SQL 查询的结果

sql - 在 SQL 中复制父子结构

sql - PostgreSQL 将一列的所有值更新为大写

java - 如何创建同时在主表行和具有 OneToMany 关系的子行中进行搜索的 JPA 查询

SQL师给出错误答案

java - 安卓/SQL服务器: Set Text to "No time" if the data at database is NULL

sql - 当您有这样的发票表时是否需要付款表?