• T-Sql 递归查询(给定节点查所有父节点、所有子节点的方法)


    -- 查找所有父节点
    with tab as
    (
     select Type_Id,ParentId,Type_Name from Sys_ParamType_V2_0 where Type_Id=316--子节点
     union all
     select b.Type_Id,b.ParentId,b.Type_Name 
     from
      tab a,--子节点数据集
      Sys_ParamType_V2_0 b  --父节点数据集
     where a.ParentId=b.Type_Id  --子节点数据集.parendID=父节点数据集.ID
    )
    select * from tab;
     
    
    -- 查找所有子节点
    with tab as
    (
     select Type_Id,ParentId,Type_Name from Sys_ParamType_V2_0 where Type_Id=1--父节点
     union all
     select b.Type_Id,b.ParentId,b.Type_Name 
     from
      tab a,--父节点数据集
      Sys_ParamType_V2_0 b--子节点数据集 
     where b.ParentId=a.Type_Id  --子节点数据集.ID=父节点数据集.parendID
    )
    select * from tab;
    
     
    
    --查找从子节点到定级节点的路径
    with tab as
    (
     select Type_Id,ParentId,Type_Name,cast(Type_Id as varchar(100)) as fulltypeid
     from SKU_ProductType where Type_Id=423--子节点
     union all
     select
       b.Type_Id,b.ParentId,b.Type_Name,
       cast(a.fulltypeid+','+cast(b.Type_Id as nvarchar(100)) as varchar(100)) as fulltypeid
     from
      tab a,--子节点数据集
      SKU_ProductType b  --父节点数据集
     where a.ParentId=b.Type_Id  --子节点数据集.parendID=父节点数据集.ID
    )
    select * from tab ;
    
    --------------结果--------------
    423    410   蜂花粉      423
    410    347   蜂产品      423,410
    347    5      营养食品   423,410,347
    5        0      健康保健   423,410,347,5

    实际

    WITH tree AS(
          SELECT ID,PID,0 as level,cast(ID as varchar(1000)) fullid,CAST(AREA_NAME as varchar(1000)) fullname
          FROM YUN_BASE_AREA
          WHERE PID='0'
    
          UNION ALL
          SELECT child.ID,child.PID,parent.level+1,cast(fullid+','+child.ID as varchar(1000)) fullid,cast(fullname+'>'+child.AREA_NAME as varchar(1000)) fullid
          FROM YUN_BASE_AREA as child
          inner join tree parent 
          on parent.ID=child.PID
        )
    SELECT * FROM tree order by fullname
    
    select * from YUN_BASE_AREA where AREA_NAME='亚洲'

    结果

  • 相关阅读:
    Coursera 高级数据结构与算法,北京大学
    heap 算法函数
    笛卡尔树 Cartesian tree
    POJ 1830 开关问题 异或高斯消元
    jmeterJSR223取样器和断言
    Flask JinJa2模板语法测试
    Python Flask Web 试题汇编<待续>
    jsDoc自动生成文档
    SQL 优化
    IO多路复用之select、poll、epoll的区别
  • 原文地址:https://www.cnblogs.com/niyl/p/13267533.html
Copyright © 2020-2023  润新知