zoukankan      html  css  js  c++  java
  • oracle递归查询

    语法:

    select *
    from tablename t start with column = ?
    connect by [prior] t.id = [prior] t.parentid

    例如:菜单表,表结构如下

      

    数据如下:

      

    一、从上向下查

    1、查询某个指定id的所有下级菜单

    select * from tb_menu t
    start with t."PARENT" = 1
    connect by prior t."ID" = t."PARENT"

    注:从上向下查,就是指定某个节点,查询其下所有的子节点(包含直接子节点和非直接子节点),故start with 条件接parent = ?;

      而connect by是指定递归时记录与记录间的关系;

      最重要的区分是prior:从上向下查,1作为parent,故将prior放在parent字段的另外一边,即表示查询所有的子条目

    效果图:

    2、查询某个指定id的所有下级菜单及该指定id的菜单信息

    select * from tb_menu t
    start with t.id = 1
    connect by prior t."ID" =  t."PARENT"

      注:从上向下查询,查找某个指定节点下的所有子节点和该指定节点,故start with条件指定id = ?,表示id = ?的数据开始向下查询(包含指定id条目)。

      而connect by是指定递归时记录与记录间的关系;

      最重要的区分是prior:从上向下查,1作为parent,故将prior放在parent字段的另外一边,即表示查询所有的子条目

    效果图:

    二、从下向上查询

    1、查询某个指定id的所有上级菜单

    select * from tb_menu t
    start with t.id = 42
    connect by  t."ID" = prior t."PARENT"

      注:从下向上查询,只有“包含该条记录”的查询,这点同从上向下查询不同

        prior的位置:将42看作id,获取其所有的parent,所以将prior放在parent一边

    效果图:

    三、总结

      1、从上向下查询,可以有两种结果:包含指定条目、不包含指定条目

      2、从下向上查询,只有一种个结果:包含指定条目

      3、prior的位置:

        从上向下查询:start with column = ?

            ?是作为父级,prior放在子级一边,表示查询所有的子级

        从下向上查询:start with column = ?

            ?是作为子级,prior放在父级一边,表示查询所有的父级

  • 相关阅读:
    CodeForces gym Nasta Rabbara lct
    bzoj 4025 二分图 lct
    CodeForces 785E Anton and Permutation
    bzoj 3669 魔法森林
    模板汇总——快读 fread
    bzoj2049 Cave 洞穴勘测 lct
    bzoj 2002 弹飞绵羊 lct裸题
    HDU 6394 Tree 分块 || lct
    HDU 6364 Ringland
    nyoj221_Tree_subsequent_traversal
  • 原文地址:https://www.cnblogs.com/brolanda/p/4522865.html
Copyright © 2011-2022 走看看