我正在为应用程序创建一个菜单系统,我对如何创建数据库查询感到困惑。
以下是我的表格:
绿色行是“父菜单”,其他是儿童。
我需要帮助编写一个TSQL查询,该查询将显示的数据排序为显示父项,然后是子项(如果有)。
排序顺序为:
父母然后由父母的子女,然后按顺序(数值)。
以下是我的数据库:
答案 0 :(得分: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
答案 1 :(得分:1)
解决方案(sqlfiddle demo):
WITH RecursiveCTE
AS(
SELECT crt.id, crt.title, crt.parentID, crt.[order],
-- 1 AS menu_level,
CONVERT(VARCHAR(8000), '/' + CONVERT(VARCHAR(11),crt.[order]) + '/') AS overall_order
FROM @Menu crt
WHERE crt.parentID = 0
UNION ALL
SELECT cld.id, cld.title, cld.parentID, cld.[order],
-- prt.menu_level + 1 AS menu_level,
prt.overall_order + CONVERT(VARCHAR(11),cld.[order]) + '/'
FROM @Menu cld -- cld = Child
INNER JOIN RecursiveCTE prt ON cld.parentID = prt.id -- prt = Parent
)
SELECT *
,CONVERT(HIERARCHYID, overall_order) AS hid_overall_order -- SQL2008+ You could convert to HIERARCHYID
FROM RecursiveCTE
ORDER BY hid_overall_order
OPTION(MAXRECURSION 0) -- Default MAXRECURSION is 100
结果:
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/