如何使用多级SQL创建类别树层次结构?

时间:2017-08-21 12:05:33

标签: sql sql-server tree categories hierarchy

我有一个代表类别层次结构的表,层次结构顶部的元素的父ID为0。 CatID列中有超过54K的唯一ID。每个ID都可以是另一个ID的父级。这些类别深入8级。 该表如下:

CatID   ParentID  CatName
1       0         Home
.       .         .
.       .         .
20      1         Vehicles
.       .         .
35      20        SUV
36      20        Motorbikes
.       .         .
90      35        BMW
91      35        Toyota
.       .         .
234     91        Land Cruiser

这是我想要实现的结果:

Cat0   Cat1       Cat2        Cat3    Cat4         Cat5   Cat6   Cat7
Home   Vehicles   SUV         Toyota  LandCruiser
Home   Vehicles   SUV         BMW            
Home   Vehilces   Motorbikes
.      .           .

我该怎么做?我是否需要某种循环来查看所有ID?

以前曾问过similar question,所以我使用相同的表结构来解释我的观点,但答案并不完全是我正在寻找的。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这是:

SELECT
    L0.CatName AS Cat0,
    L1.CatName AS Cat1,
    L2.CatName AS Cat2,
    L3.CatName AS Cat3,
    L4.CatName AS Cat4,
    L5.CatName AS Cat5,
    L6.CatName AS Cat6,
    L7.CatName AS Cat7
FROM
    YourTable AS L0
    LEFT JOIN YourTable AS L1
    ON L0.CatID = L1.ParentID
    LEFT JOIN YourTable AS L2
    ON L1.CatID = L2.ParentID
    LEFT JOIN YourTable AS L3
    ON L2.CatID = L3.ParentID
    LEFT JOIN YourTable AS L4
    ON L3.CatID = L4.ParentID
    LEFT JOIN YourTable AS L5
    ON L4.CatID = L5.ParentID
    LEFT JOIN YourTable AS L6
    ON L5.CatID = L6.ParentID
    LEFT JOIN YourTable AS L7
    ON L6.CatID = L7.ParentID
WHERE
    L0.ParentID = 0