oracle connect by用法篇

来源:互联网 发布:图片纠偏软件 编辑:程序博客网 时间:2024/06/05 15:14

1.基本语法

select * from table [start with condition1]    connect by [prior] id=parentid1

一般用来查找存在父子关系的数据,也就是树形结构的数据;其返还的数据也能够明确的区分出每一层的数据。

  • start with condition1 是用来限制第一层的数据,或者叫根节点数据;以这部分数据为基础来查找第二层数据,然后以第二层数据查找第三层数据以此类推。
  • connect by [prior] id=parentid 这部分是用来指明oracle在查找数据时以怎样的一种关系去查找;比如说查找第二层的数据时用第一层数据的id去跟表里面记录的parentid字段进行匹配,如果这个条件成立那么查找出来的数据就是第二层数据,同理查找第三层第四层…等等都是按这样去匹配。


prior还有一种用法:

select * from table [start with condition1]    connect by id= [prior] parentid1

其他特性

  • level关键字,代表树形结构中的层级编号;第一层是数字1,第二层数字2,依次递增。
  • CONNECT_BY_ROOT方法,能够获取第一层集结点结果集中的任意字段的值;例CONNECT_BY_ROOT(字段名)。

2.demo例子


2.1 从根节点查找叶子节点

select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 0connect by prior t.id = t.fid;
这里写图片描述

2.2 从叶子节点查找上层节点

--第一种,修改prior关键字位置select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 4connect by t.id = prior t.fid;--第二种,prior关键字不动 调换后面的id=fid逻辑关系的顺序select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 4connect by prior t.fid = t.id;
这里写图片描述

3.常用例子


3.1 查询人员所属的二级机构部门代码

select distinct deptno    from emp_deptwhere dept_level = '2'     connect by dept_no = prior parent_dept_nostart with dept_no  in ( select  deptno  from emp where name='张珊'; )

3.2 字符串分割

比如说分割01#02#03#04这种有规律的字符串

select REGEXP_SUBSTR('01#02#03#04', '[^#]+', 1, rownum) as newport     from dual connect by rownum <= REGEXP_COUNT('01#02#03#04', '[^#]+');

这里写图片描述