zoukankan      html  css  js  c++  java
  • sql无限级树型查询

    表结构如下:

    表数据如下:

    一提到无限级,很容易想到递归,使用sql 的CET语法如下

    with menu(Id,Name,ParentId,Level)
    as
    (
    select Id,Name,ParentId,0 as Level from dbo.Category where ParentId is Null
    Union All 
    Select A.Id,A.Name,A.ParentId,B.Level+1 from dbo.Category A inner join menu B
    on A.ParentId=B.Id
    )
    select * from menu order by Id
    

      查询结果如下图:

    看到这样的结果,大失所望,继续修改查询语句

    with menu(Id,Name,ParentId,Level,px,px2)
    as
    (
    select Id,Name,ParentId,0 as Level,Id px, cast(Id as nvarchar(4000)) px2  from dbo.Category where ParentId is Null
    Union All 
    Select A.Id,A.Name,A.ParentId,B.Level+1 ,B.px,B.px2+ltrim(A.Id) from dbo.Category A inner join menu B
    on A.ParentId=B.Id
    )
    select * from menu order by px,px2 
    

      再看一下运行结果:

  • 相关阅读:
    NYOJ 542 试制品(第五届河南省省赛)
    714-Card Trick
    716-River Crossing
    1248-海岛争霸
    51Nod
    51Nod
    NYOJ_1274_信道安全
    ZZNU 2095 : 我只看看不写题
    前端-HTML标签
    python 17篇 unittest单元测试框架
  • 原文地址:https://www.cnblogs.com/bubugao/p/CET.html
Copyright © 2011-2022 走看看