向下填充顶层详细信息层次结构

ttisahbt  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(249)

我想在层次结构中填充顶层细节。我有两张table。
主表

+-----+------+--------+
| ID  | Name | NodeID |
+-----+------+--------+
| 1   | A    | 1      |
+-----+------+--------+
| 2   | B    | 2      |
+-----+------+--------+
| 3   | C    | 3      |
+-----+------+--------+

关系表

+----+---------+----------+
| ID | ChildID | ParentID |
+----+---------+----------+
| 1  | 11      | 1        |
+----+---------+----------+
| 2  | 12      | 11       |
+----+---------+----------+
| 3  | 13      | 12       |
+----+---------+----------+
| 4  | 21      | 2        |
+----+---------+----------+
| 5  | 22      | 21       |
+----+---------+----------+

我希望输出如下:

+------+--------+---------+----------+
| Name | NodeID | ChildID | ParentID |
+------+--------+---------+----------+
| A    | 1      | 11      | 1        |
+------+--------+---------+----------+
| A    | 1      | 12      | 11       |
+------+--------+---------+----------+
| A    | 1      | 13      | 12       |
+------+--------+---------+----------+
| B    | 2      | 21      | 2        |
+------+--------+---------+----------+
| B    | 2      | 22      | 21       |
+------+--------+---------+----------+

我已经使用cte编写了递归sql,但是它没有给出预期的结果。

;WITH relation_cte (childid, parentid) 
     AS (SELECT childid, 
                parentid 
         FROM   @RelationTable AS RT1 
                INNER JOIN @MainTable AS MT 
                        ON MT.nodeid = RT1.parentid 
         UNION ALL 
         SELECT RT2.childid, 
                RT2.parentid 
         FROM   @RelationTable AS RT2 
                INNER JOIN relation_cte AS REL_CTE 
                        ON REL_CTE.childid = RT2.parentid) 
SELECT MT.managername, MT.nodeid, REL_CTE.childid, REL_CTE.parentid 
FROM   relation_cte AS REL_CTE 
       LEFT OUTER JOIN @MainTable AS MT 
                    ON MT.nodeid = REL_CTE.parentid

有人能帮我学sql吗?谢谢。

gopyfrb3

gopyfrb31#

将toplevelid列添加到cte中,不要忘记order by子句:

;WITH relation_cte (childid, parentid, toplevelid) AS (
    SELECT 
        RT1.childid, 
        RT1.parentid, 
        MT.nodeid 
    FROM   
        @RelationTable AS RT1 
        INNER JOIN @MainTable AS MT ON MT.nodeid = RT1.parentid 
    UNION ALL 
    SELECT 
        RT2.childid, 
        RT2.parentid,
        REL_CTE.toplevelid
    FROM
        @RelationTable AS RT2 
        INNER JOIN relation_cte AS REL_CTE ON REL_CTE.childid = RT2.parentid
) 
SELECT 
    MT.name, REL_CTE.toplevelid, REL_CTE.childid, REL_CTE.parentid 
FROM
    relation_cte AS REL_CTE 
    LEFT OUTER JOIN @MainTable AS MT ON MT.nodeid = REL_CTE.toplevelid
ORDER BY 2

相关问题