我正在为一个应用程序创建一个菜单系统,而且我有点在如何去创建数据库查询。为菜单系统编写SQL查询
这里是我的表是这样的:
绿色行是“父菜单”和其他人是儿童。
我需要帮助编写一个TSQL查询,对显示的父数据以及子数据(如果有的话)进行排序。
排序顺序将是:
父然后通过父的儿童,然后通过阶(数值)。
这里是我的数据库看起来像:
我正在为一个应用程序创建一个菜单系统,而且我有点在如何去创建数据库查询。为菜单系统编写SQL查询
这里是我的表是这样的:
绿色行是“父菜单”和其他人是儿童。
我需要帮助编写一个TSQL查询,对显示的父数据以及子数据(如果有的话)进行排序。
排序顺序将是:
父然后通过父的儿童,然后通过阶(数值)。
这里是我的数据库看起来像:
解决方案(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/
为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
至少你可以执行'SELECT @@ VERSION'。 –