0
Id | MenuName      | vc_Link | SubMenu1 | IsMainMenu | TypeOfMenu
-----------------------------------------------------------------------
1  | Home          |  NULL   |  NULL    |     1      |     0
2  | Projects      |  NULL   |  NULL    |     1      |     0
4  | Pr1           |  NULL   |   2      |     0      |     1
5  | Homesub       |  NULL   |   1      |     0      |     1
6  | Pr1Sub1       |  NULL   |   4      |     0      |     2

以上是我的表结构。

  1. MenuName 是菜单和子菜单的名称
  2. SubMenu1 是子菜单属于特定菜单,其 id 保存为 submenu1
  3. MainMenu 有点知道是菜单还是子菜单。
  4. typeofmenu 是那个
0 means main menu
1 means submenu
2 means submenu's submenu

现在我的问题是我想显示如下

   1 Home
      5 HomeSub
   2 Projects
     4 Pr1
         6 Pr1Sub1

   Id | MenuName      | vc_Link | SubMenu1 | IsMainMenu | TypeOfMenu
    -----------------------------------------------------------------------
    1  | Home          |  NULL   |  NULL    |     1      |     0
    5  | HomeSub       |  NULL   |  1       |     0      |     1
    2  | Projects      |  NULL   |  NULL    |     1      |     0
    4  | Pr1           |  NULL   |   2      |     0      |     1
    6  | Pr1Sub1       |  NULL   |   4      |     0      |     2

怎么分组这样?只有在像这样分组之后,我才能将此查询的结果作为显示菜单及其子菜单的树结构。

4

1 回答 1

2

像这样的东西:

with menu_tree (id, menuname, level, sort_path) as (
   select id, 
          cast(menuname as varchar(max)), 
          1 as level,
          cast(id as varchar(max)) as sort_path
   from menus
   where submenu1 is null
   union all
   select m.id, 
          cast(replicate('_', p.level * 2) + m.menuname as varchar(max)) as menuname, 
          p.level + 1,
          p.sort_path + '_' + cast(m.id as varchar(max))
   from menus m
     join menu_tree p on p.id = m.submenu1
)  
select id, menuname
from menu_tree
order by sort_path;

SQLFiddle:http ://sqlfiddle.com/#!3/6c4ba/1

于 2013-01-25T12:45:46.337 回答