SQL递归查找-oracle

示例表

字段

字段名字段注释
org_code机构代码
org_name机构名称
parent_org_code上级机构代码

建表SQL

-- Create table
create table t_demo_org
(
  org_code        varchar(32),
  org_name        varchar(100),
  parent_org_code varchar(32)
)
;
-- Add comments to the columns 
comment on column t_demo_org.org_code
  is '机构代码';
comment on column t_demo_org.org_name
  is '机构名称';
comment on column t_demo_org.parent_org_code
  is '上级机构代码';

示例数据

数据预览

机构代码机构名称上级机构代码
org_code1org_name1org_code0
org_code2org_name2org_code1
org_code3org_name3org_code2
org_code4org_name4org_code3
org_code5org_name5org_code4
org_code6org_name6org_code5
org_code7org_name7org_code6
org_code8org_name8org_code7
org_code9org_name9org_code8
org_code10org_name10org_code9

新增SQL

insert into t_demo_org values ('org_code1', 'org_name1', 'org_code0');
insert into t_demo_org values ('org_code2', 'org_name2', 'org_code1');
insert into t_demo_org values ('org_code3', 'org_name3', 'org_code2');
insert into t_demo_org values ('org_code4', 'org_name4', 'org_code3');
insert into t_demo_org values ('org_code5', 'org_name5', 'org_code4');
insert into t_demo_org values ('org_code6', 'org_name6', 'org_code5');
insert into t_demo_org values ('org_code7', 'org_name7', 'org_code6');
insert into t_demo_org values ('org_code8', 'org_name8', 'org_code7');
insert into t_demo_org values ('org_code9', 'org_name9', 'org_code8');
insert into t_demo_org values ('org_code10', 'org_name10', 'org_code9');

递归查找

为了方便查看数据,以第5条数据为分界点。

SQL

oracle

select *
  from t_demo_org o
  -- 指定起始查询条件
 start with o.org_code = 'org_code5'
 -- 关联查询条件,以当前数据为基准,【向上】递归查询
connect by o.org_code = prior o.parent_org_code;
-- 关联查询条件,以当前数据为基准,【向下】递归查询
-- connect by o.parent_org_code = prior o.org_code;

postgresql

 with RECURSIVE tmp as (
  -- 指定起始查询条件
  select * from t_demo_org o where o.org_code = 'org_code1'
  union 
 -- 关联查询条件,以当前数据为基准,【向上】递归查询
  select po.* from t_demo_org po join tmp on  po.org_code = tmp.parent_org_code
 -- 关联查询条件,以当前数据为基准,【向下】递归查询
 -- select po.* from t_demo_org po join tmp on  po.parent_org_code = tmp.org_code
 ) select * from tmp

结果

向上递归查询

机构代码机构名称上级机构代码
org_code5org_name5org_code4
org_code4org_name4org_code3
org_code3org_name3org_code2
org_code2org_name2org_code1
org_code1org_name1org_code0

向下递归查询

机构代码机构名称上级机构代码
org_code5org_name5org_code4
org_code6org_name6org_code5
org_code7org_name7org_code6
org_code8org_name8org_code7
org_code9org_name9org_code8
org_code10org_name10org_code9
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇