2013-08-25 48 views
0

我正在为一个应用程序创建一个菜单系统,而且我有点在如何去创建数据库查询。为菜单系统编写SQL查询

这里是我的表是这样的:

enter image description here

绿色行是“父菜单”和其他人是儿童。

我需要帮助编写一个TSQL查询,对显示的父数据以及子数据(如果有的话)进行排序。

排序顺序将是:

父然后通过父的儿童,然后通过阶(数值)。

这里是我的数据库看起来像:

enter image description here

+0

至少你可以执行'SELECT @@ VERSION'。 –

回答

1

解决方案(sqlfiddle demo) :

​​个

结果:

id title   parentID order overall_order 
-- --------------- ----------- ----- ------------- 
11 Home   0   1  /1/ 
12 Settings  0   2  /2/ 
13 Change Password 12   4  /2/4/ 
14 Update Profile 12   5  /2/5/ 
15 Search   0   3  /3/ 
16 Options   15   6  /3/6/ 
+0

我可以把最终的输出到XML? FOR XML PATH('menu'),TYPE,ELEMENTS,ROOT('root') – SBB

+0

@CarlHussey:我没有看到任何关于XML输出的要求。你可以尝试:-) –

+0

好吧,我试着在最后一个选择语句后添加它,它不喜欢它 – SBB

1

为SQL Server,你可以做递归查询,像这样:

with cte as (
    select 
     m.id, m.parent_id, m.title, 
     right('00000' + cast(m.ordering as nvarchar(max)), 5) as ordering 
    from menu as m 
    where m.parent_id is null 

    union all 

    select 
     m.id, m.parent_id, m.title, 
     c.ordering + '.' + right('00000' + cast(m.ordering as nvarchar(max)) , 5) as ordering 
    from menu as m 
     inner join cte as c on c.id = m.parent_id 
) 
select * 
from cte 
order by ordering 

sql fiddle demo

+0

嗯,我仍然有点困惑如何适应这个我的表:/ – SBB

+0

为什么?只需添加其他列来选择 –

+0

它似乎给了我更多的数据比我期望的最后:http://carl.me/menu2.png – SBB