如何创建多级分类树层次结构SQL?
How to Create Category Tree Hierarchy with Multiple Levels SQL?
我有一个 table 表示类别层次结构,层次结构顶部的元素的父 ID 为 0。
CatID 列中有超过 54K 个唯一 ID。每个 ID 都可以是另一个 ID 的父级。类别深入 8 个级别。
table 如下例:
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,所以我用同样的table结构来解释我的观点,但答案并不是我要找的。
有人可以帮忙吗?
这里是:
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
我有一个 table 表示类别层次结构,层次结构顶部的元素的父 ID 为 0。 CatID 列中有超过 54K 个唯一 ID。每个 ID 都可以是另一个 ID 的父级。类别深入 8 个级别。 table 如下例:
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,所以我用同样的table结构来解释我的观点,但答案并不是我要找的。
有人可以帮忙吗?
这里是:
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