0

我正在为应用程序创建一个菜单系统,但我对如何创建数据库查询有点困惑。

这是我的表的样子:

在此处输入图像描述

绿色行是“父菜单”,其他是子菜单。

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

排序顺序为:

父级,然后是父级的子级,然后是顺序(数值)。

这是我的数据库的样子:

在此处输入图像描述

4

2 回答 2

2

对于 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

于 2013-08-25T05:44:09.717 回答
1

解决方案(sqlfiddle 演示):

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/
于 2013-08-25T07:06:09.450 回答