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 
    

      再看一下运行结果:

  • 相关阅读:
    NOI 模拟赛
    bzoj 4998 星球联盟
    bzoj 4545 DQS 的 Trie
    loj #161 子集卷积
    bzoj 5093 图的价值
    bzoj 4299 Codechef FRBSUM
    NOI 模拟赛
    WC2018 州区划分
    CSP 2020 T2 动物园
    CSP 2020 T1 儒略日
  • 原文地址:https://www.cnblogs.com/bubugao/p/CET.html
Copyright © 2011-2022 走看看