如何使用多级SQL创建类别树层次结构? [英] How to Create Category Tree Hierarchy with Multiple Levels SQL?

查看:211
本文介绍了如何使用多级SQL创建类别树层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
.      .           .

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

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.

有人可以帮忙吗?

推荐答案

在这里是:

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

这篇关于如何使用多级SQL创建类别树层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆