输入banner图图片脚本导航/分类

Oracle递归查询

…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)

 

Oracle递归查询

标签: