ORACLE 递归查询的两种方法。

1. 我们建一个表 test2 举例说明 oracle 递归查询的两种方法。

数据结构如下:

2. 我们的目标是查找A1下面所有的子节点和所处层级。

A.通用做法:写一个递归SQL 如下

select t.*, level
  from test2 t
 start with t.father = 'A1'
connect by t.father = prior t.child
 order by level

结果:

B.替代做法:

with all_test(father,
child,
levelno) as
 (select t.father, t.child, 1
    from test2 t
   where t.father = 'A1'
  union all
  select t2.father, t2.child, at.levelno + 1
    from test2 t2, all_test at
   where at.child = t2.father)

select * from all_test

结果:

3. 从以上两种结果来看,结果一样。经测试数据量很大的情况下,B,替代做法效率较高。

发布了14 篇原创文章 · 获赞 2 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章