SQL查询2个表构成类目树

SQL Query of 2 Tables forming a category tree

我有2张桌子。第一个是类别的 ID。

类别

CategoryID ParentID
1 0
2 1
3 1
4 2
5 3
6 5

类别名称

CategoryID Name
1 Top
2 Cat1
3 Cat2
4 Cat3
5 Another1
6 RandCat

需要生成将 return 类别树的查询。

CategoryID Cat Name Parent Cat Name
1 Top
2 Cat1 Top
3 Cat2 Top
4 Cat3 Cat1
5 Another1 Cat2
6 RandCat Another1

我们最多可以有 3 层子类别,并且必须根据需要增加 table。

感谢您的帮助!

这看起来像 JOINs:

select c.categoryid, cn.name, cnp.name
from category c left join
     categoryname cn
     on cn.categoryid = c.categoryid left join
     categoryname cnp
     on cnp.categoryid = c.parentid;

您需要与基础 table 左连接作为 category_name

Select cn.categoryid, cn.cat_name,
       Cnp.cat_name as parent_category
  From category_name cn
  Left join category c on c.categoryid = cn.categoryid
  Left join category_name cnp on cnp.categoryid = c.parentid;