Oracle高级查询之CONNECT BY
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Oracle高级查询之CONNECT BY相关的知识,希望对你有一定的参考价值。
为了方便大家学习和测试,所有的例子都是在Oracle自带用户Scott下建立的。
Oracle中的select语句可以用start with ... connect by prior ...子句实现递归查询,connect by 是结构化查询中用到的,其基本语法是:
select ... fromwhere <过滤条件,用于对返回的所有记录进行过滤>
start with <根结点的限定语句,当然可以放宽限定条件,以取得多个根结点,实际就是多棵树>
connect by [prior] <连接条件,其中用prior表示上一条记录,比如:connect by prior t.id = t.parent_id就是说上一条记录的id 是本条记录的parent_id,即本记录的父亲是上一条记录>
下面我们直接来看实例,查询‘KING‘的所有下属雇员。SQL语句如下:
- select *
- from scott.emp e
- start with e.ename = ‘KING‘
- connect by prior e.empno = e.mgr;
- select *
- from scott.emp e
- start with e.ename = ‘SMITH‘
- connect by e.empno = prior e.mgr;
1、sys_connect_by_path函数
语法:sys_connect_by_path(列名, ‘分隔符‘)。
作用:从start with的地方开始遍历,将遍历到的路径根据函数中的分隔符,组成一个新的字符串。
- select sys_connect_by_path(ename, ‘/‘) ename_tree
- from scott.emp
- start with ename = ‘KING‘
- connect by mgr = prior empno;
- select max(ltrim(sys_connect_by_path(column_name, ‘|‘), ‘|‘)) column_names
- from (select column_name, rownum rnum
- from user_tab_columns
- where table_name = ‘EMP‘)
- start with rnum = 1
- connect by rnum = rownum;
2、level:在结构化查询结果中,每一行都是结构中的一个节点,level表示该节点在结构中的层次,根节点为1,根节点的子节点为2,以此类推。
下面SQL语句很直观的展示效果:
- select ename, sys_connect_by_path(ename, ‘/‘) ename_tree, level
- from scott.emp
- start with ename = ‘KING‘
- connect by mgr = prior empno;
3、connect_by_root:用在列名之前,返回当前节点的根节点对应列的值。connect_by_isleaf:返回当前节点是否为叶子节点,“是”返回1,“否”返回0。
下面SQL语句很直观的展示效果:
- select sys_connect_by_path(ename, ‘/‘) ename_tree,
- connect_by_root ename as root,
- connect_by_isleaf as isleaf
- from scott.emp e
- start with e.ename = ‘KING‘
- connect by prior e.empno = e.mgr;
创建表,初始化数据;
- CREATE TABLE TB_COMPANY
- (
- COMPANY_ID INTEGER PRIMARY KEY,
- COMPANY VARCHAR2(256),
- UP_COMPANYID INTEGER
- );
- INSERT INTO TB_COMPANY VALUES (0, ‘总公司‘, NULL);
- INSERT INTO TB_COMPANY VALUES (1, ‘北京分公司‘, 0);
- INSERT INTO TB_COMPANY VALUES (2, ‘上海分公司‘, 0);
- INSERT INTO TB_COMPANY VALUES (3, ‘海淀区分部‘, 1);
- INSERT INTO TB_COMPANY VALUES (4, ‘东城区分部‘, 1);
- INSERT INTO TB_COMPANY VALUES (5, ‘黄埔区分部‘, 2);
- INSERT INTO TB_COMPANY VALUES (6, ‘静安区分部‘, 2);
- COMMIT;
全部数据:
递归查询SQL:
- SELECT (RPAD(‘ ‘, 2*(LEVEL-1), ‘-‘ ) || COMPANY) COMPANY_NAME, CONNECT_BY_ROOT COMPANY, CONNECT_BY_ISLEAF, LEVEL , SYS_CONNECT_BY_PATH(COMPANY, ‘/‘)
- FROM TB_COMPANY
- START WITH UP_COMPANYID IS NULL
- CONNECT BY PRIOR COMPANY_ID = UP_COMPANYID;
结果:
说明:
1. CONNECT_BY_ROOT 返回当前节点的最顶端节点
2. CONNECT_BY_ISLEAF 判断是否为叶子节点,如果这个节点下面有子节点,则不为叶子节点
3. LEVEL 伪列表示节点深度
4. SYS_CONNECT_BY_PATH函数显示详细路径,并用“/”分隔
递归查询SQL:
- SELECT * FROM TB_COMPANY START WITH COMPANY_ID = 1 CONNECT BY PRIOR COMPANY_ID = UP_COMPANYID;
结果:
以上是关于Oracle高级查询之CONNECT BY的主要内容,如果未能解决你的问题,请参考以下文章
Oracle高级查询之over(partition by..)
Oracle高级查询之over(partition by...)
Oracle高级查询之over(partition by...)