您的位置:首页 >生活 >

Oracle中递归查询(START WITH……CONNECT BY……)

2023-08-26 02:49:12 来源:个人图书馆-jacklopy

在Oracle中START WITH……CONNECT BY……一般用来查找存在父子关系的数据,也就是树形结构的数据。

以下用的表结构来源于测试用例数据。

1)最基本查询


(资料图片)

--从PARENT为空开始扫描   SELECT * FROM tab_connect_by A   START WITH A.PARENT IS NULL CONNECT BY PRIOR A.CHILD = A.PARENT;
SELECT * FROM tab_connect_by A   WHERE A.PARENT = "5"--条件3  START WITH A.PARENT = "15" --条件1CONNECT BY PRIOR A.CHILD = A.PARENT;--条件2

查询结果如下:

根据结果可以看出,条件的优先级,根据start with后的条件查询第一条数据,然后根据connect by的条件,利用先决条件(start with)查询的child为起点作为下条数据的父节点递归查询所有的数据;

其中where是根据最后所有递归出的数据再进行过滤。

2)prior的用法

--PRIOR在等号前面,向下递归,查找对应的子节点 SELECT * FROM tab_connect_by A  START WITH A.PARENT = "15" CONNECT BY PRIOR A.CHILD = A.PARENT;--PRIOR在等号后面,向上递归,查找对应的子节点 SELECT * FROM tab_connect_by A  START WITH A.PARENT = "15" CONNECT BY A.CHILD = PRIOR A.PARENT; SELECT * FROM tab_connect_by A  START WITH A.PARENT = "15" CONNECT BY PRIOR A.PARENT = A.CHILD; 

查询结果如下:根据案例可以理解一下prior的用法。

3)其他

SELECT A.PARENT       ,A.CHILD       ,LEVEL "层次"        ,SYS_CONNECT_BY_PATH(CHILD, "<-") "合并层次"        ,PRIOR A.CHILD "父节点"        ,CONNECT_BY_ROOT A.CHILD "根节点"        ,DECODE(CONNECT_BY_ISLEAF, 1, A.CHILD, NULL) "子节点"        ,DECODE(CONNECT_BY_ISLEAF, 1, "是", "否") "是否子节点"    FROM TAB_CONNECT_BY A   START WITH A.PARENT IS NULL --从PARENT为空开始扫描  CONNECT BY PRIOR A.CHILD = A.PARENT --以CHILD为父列连接PARENT   ORDER SIBLINGS BY CHILD DESC --对层次排序  ; 

查询结果如下:

4)数字序列结果集:LEVEL、ROWNUM

SELECT LEVEL FROM DUAL CONNECT BY LEVEL <= 10;SELECT ROWNUM FROM DUAL CONNECT BY ROWNUM <= 10;

关键词: