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

4

我有一个表格,表示类别层次结构,位于层次结构顶部的元素的父级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吗?
以前有类似的问题被问过,所以我使用了相同的表结构来解释我的观点,但答案并不完全符合我的要求。
请问有人能帮忙吗?

类别层次结构始终不超过8个级别吗?即没有Cat8,或者您不希望检索到更深的成员? - Mislav Zic
嗨 @MislavZic!是的,层次结构始终有8个级别。 - Maciej
我相信John的答案正是你所需要的。 - Zohar Peled
1个回答

4

这是:

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

哇,这么简单啊? :D 非常感谢 @MislavZic!当然完美运行! - Maciej
我很高兴能帮到你。 :) - Mislav Zic
你好,这个能在MS-Access中工作吗?我尝试过了。 - Valter Ekholm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接