How to Create Category Tree Hierarchy with Multiple Levels SQL? [duplicate]

独自空忆成欢 提交于 2020-01-03 00:54:50

问题


I have a table which represents a category hierarchy and the element at top of the hierarchy has the parent id as 0. There are over 54K unique IDs in the CatID Column. Each ID can be a parent of another. The categories go 8 levels deep. The table is as the exaple below:

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

And this is the result I would like to achieve:

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

How can I do this? Do I need some sort of loop to go through all IDs?

There was a similar question asked before, so I've used the same table structure to explain my point, but the answer is not exactly what I'm looking for.

Can anyone help please?


回答1:


Here it is:

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


来源:https://stackoverflow.com/questions/45796694/how-to-create-category-tree-hierarchy-with-multiple-levels-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!