原创

Oracle 中的树查询和 connect by

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://wxy0327.blog.csdn.net/article/details/53927297
  • Oracle 中的树查询和 connect by

    使用 connect by 和 start with 来建立类似于树的报表并不难,只要遵循以下基本原则即可:

    使用 connect by 时各子句的顺序应为:
    select
    from
    where
    start with
    connect by
    order by
  • prior 使报表的顺序为从根到叶(如果 prior 列是父辈)或从叶到根(如果 prior 列是后代)。
  • where 子句可以从树中排除个体,但不排除它们的子孙(或者祖先,如果 prior 列是后代)。
  • connect by 中的条件(尤其是不等于)消除个体和它所有的子孙(或祖先,依赖于怎样跟踪树)。
  • connect by 不能与 where 子句中的表连接在一起使用。



下面是几个例子


1. 从根到叶遍历
SELECT n_parendid, n_name, (LEVEL - 1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
START WITH n_id = 0
CONNECT BY n_parendid = PRIOR n_id;

2. 从叶到根遍历
SELECT n_parendid, n_name, (LEVEL - 1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
START WITH n_id = 300
CONNECT BY n_id = PRIOR n_parendid;


3. 排除个体,但不排除它们的子孙
SELECT n_parendid, n_name, (LEVEL - 1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL AND n_id != 2
START WITH n_id = 0
CONNECT BY n_parendid = PRIOR n_id;

4. 消除个体和它所有的子孙
SELECT n_parendid, n_name, (LEVEL - 1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
START WITH n_id = 0
CONNECT BY n_parendid = PRIOR n_id AND n_id != 2;


5. 改变显示顺序
SELECT n_parendid, n_name, (LEVEL - 1), n_id
FROM navigation
WHERE n_parendid IS NOT NULL
START WITH n_id = 0
CONNECT BY n_parendid = PRIOR n_id
ORDER BY n_viewnum DESC;
 

文章最后发布于: 2016-12-29 14:12:26
展开阅读全文
0 个人打赏
私信求帮助

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览