Oracle递归查询

1.语法结构:

select…start with…connect by…prior

例如:有一个单位(unit)表 有三个字段 ID ,NAME,PARENTID(单位ID,单位名称,上级的单位ID)  

  1.1 查询该单位下面的所有单位

select t.id,t.name,t.parentid from unit t start with t.id='单位的ID' connect by prior  t.id= t.parentid

 1.2 查询该单位上面的所有单位

select t.id,t.name,t.parentid from unit t start with t.id='单位的ID' connect by  t.id= prior t.parentid

2.备注:

start with 标识从哪个地方开始查  

prior  标识往上查还是往下查

3.拓展:

 递归查询往往伴随着兄弟之间进行排序,这时候我们会用到:ORDER SIBLINGS BY

例如:查询所有的单位并对同级别的单位按拼音排序

select t.id,t.name,t.parentid from unit t start with t.id='单位的ID' connect by prior  t.id= t.parentid ORDER SIBLINGS BY nlssort(t.name,'NLS_SORT=SCHINESE_PINYIN_M')
原文地址:https://www.cnblogs.com/bweb/p/4832890.html