• Oracle递归查询父子兄弟节点


    1、查询某节点下所有后代节点(包括各级父节点)

    1 // 查询id为101的所有后代节点,包含101在内的各级父节点
    2 select t.* from SYS_ORG t start with id = '101' connect by parent_id = prior id

    2、查询某节点下所有后代节点(不包含各级父节点)

    1 select t.*
    2   from SYS_ORG t
    3  where not exists (select 1 from SYS_ORG s where s.parent_id = t.id)
    4  start with id = '101'
    5 connect by parent_id = prior id

    3、查询某节点所有父节点(所有祖宗节点) 

    1 select t.*
    2   from SYS_ORG t
    3  start with id = '401000501'
    4 connect by prior parent_id = id

    4、查询某节点所有的兄弟节点(亲兄弟)

    1 select * from SYS_ORG t
    2 where exists (select * from SYS_ORG s where t.parent_id=s.parent_id and s.id='401000501')

    5、查询某节点所有同级节点(族节点),假设不设置级别字段

    1 with tmp as(
    2       select t.*, level leaf        
    3       from SYS_ORG t               
    4       start with t.parent_id = '0'     
    5       connect by t.parent_id = prior t.id)
    6 select *                               
    7       from tmp                             
    8 where leaf = (select leaf from tmp where id = '401000501');

    这里使用两个技巧,一个是使用了level来标识每个节点在表中的级别,还有就是使用with语法模拟出了一张带有级别的临时表

     6、查询某节点的父节点及兄弟节点(叔伯节点)

    with tmp as(
        select t.*, level lev
        from SYS_ORG t
        start with t.parent_id = '0'
        connect by t.parent_id = prior t.id)  
    select b.*
    from tmp b,(select *
                from tmp
                where id = '401000501' and lev = '2') a
    where b.lev = '1'
     
    union all
     
    select *
    from tmp
    where parent_id = (select distinct x.id
                    from tmp x, --祖父
                         tmp y, --父亲
                         (select *
                          from tmp
                          where id = '401000501' and lev > '2') z --儿子
                    where y.id = z.parent_id and x.id = y.parent_id); 

    这里查询分成以下几步。
    首先,将全表都使用临时表加上级别;
    其次,根据级别来判断有几种类型,以上文中举的例子来说,有三种情况:
    (1)当前节点为顶级节点,即查询出来的lev值为1,那么它没有上级节点,不予考虑。
    (2)当前节点为2级节点,查询出来的lev值为2,那么就只要保证lev级别为1的就是其上级节点的兄弟节点。
    (3)其它情况就是3以及以上级别,那么就要选查询出来其上级的上级节点(祖父),再来判断祖父的下级节点都是属于该节点的上级节点的兄弟节点。
    最后,就是使用union将查询出来的结果进行结合起来,形成结果集。

  • 相关阅读:
    字王20年
    [转]Birdfont 2.10 发布,字体编辑器
    vs2013编译boost库
    c++ 完成端口资料
    获取输入法输入内容及后选项的钩子
    unicode string和ansi string的转换函数及获取程序运行路径的代码
    c++实现输入法窗口自定义的代码
    在固定长方形里产生渐变
    监听某个div或其它标签的大小改变来执行相应的处理
    64位SqlServer通过链接服务器与32位oracle通讯
  • 原文地址:https://www.cnblogs.com/dahaihh-2018/p/8274617.html
Copyright © 2020-2023  润新知