类和子类sql顺序排序

时间:2013-09-03 02:35:13

标签: mysql sql left-join categories

我有以下表格

table_name:categories

id   name        parent  
16   Rash Vest   41  
17   Shorts      41  
20   Tops        41  
41   Shop        0  
47   Mens        16  
48   Womens      16  

table_name:items

id   title                 alias                 catid  
70   Rash Vest Black       rash-vest-black       47   
96   Rash Vest Red         rash-vest-red         47  
98   Rash Vest Womens Red  rash-vest-womens-red  48  

现在我想根据根树显示所有项目。

喜欢这个 主菜单: SHOP
子菜单:皮疹背心 |短裤|上衣
儿童类别:
男装
-----> Rash Vest Black
-----> Rash Vest Red
女子
-----> Rash背心女装红色

1 个答案:

答案 0 :(得分:1)

SQL-SERVER versio

;WITH groups AS
(SELECT ID
 , Name
 , ParentID
 , 0 AS Level
 , CAST(Name AS VARCHAR(255)) AS Path
 FROM Category WHERE ParentID = 0

 UNION ALL

 SELECT c.ID
 , c.Name
 , c.ParentID
 , g.Level + 1
 , CAST(CAST(g.Path AS VARCHAR(255)) + 
        CAST(' -> ' AS VARCHAR(255)) + 
        CAST(c.Name AS VARCHAR(255)) AS VARCHAR(255))
 FROM Category c 
 INNER JOIN groups g ON g.ID = c.ParentID
)

SELECT g.Name
, g.Level
, g.Path
, ISNULL(itm.Title, 'No items') AS Title
FROM groups g
LEFT JOIN Item itm ON itm.CategoryID = g.ID
ORDER BY g.Path

如果您希望显示结果有问题,那么这部分工作用户界面(您的应用程序)

SQL Fiddle例如/ testing