oracle connect by用法

oracle connect by用法

create table t_location(
       id number primary key,
       name varchar(16) not null,
       pid number not null
)
insert into t_location values(1,'华东区',0);
insert into t_location values(2,'华南区',0);
insert into t_location values(3,'福建省',1);
insert into t_location values(4,'江苏省',1);
insert into t_location values(5,'福州市',3);
insert into t_location values(6,'厦门市',3);
insert into t_location values(7,'苏州市',4);
insert into t_location values(8,'扬州市',4);
insert into t_location values(9,'广东省',2);
insert into t_location values(10,'广西省',2);
insert into t_location values(11,'广州市',9);
insert into t_location values(12,'深圳市',9);
insert into t_location values(13,'南宁市',10);
insert into t_location values(14,'桂林市',10);
--2.1 从根节点查找叶子节点
select t.*, level, CONNECT_BY_ROOT(id)
  from t_location t
 start with t.id = 1
connect by prior t.id = t.pid;

--2.2 从叶子节点查找上层节点
--第一种,修改prior关键字位置
select t.*, level, CONNECT_BY_ROOT(id)
  from t_location t
 start with t.id = 14
connect by t.id = prior t.pid;

--第二种,prior关键字不动 调换后面的id=fid逻辑关系的顺序
select t.*, level, CONNECT_BY_ROOT(id)
  from t_location t
 start with t.id = 14
connect by prior t.pid = t.id;

--查找某个结点的路由
select replace(wm_concat(name),',',' ') as addr from(
  select t.name,connect_by_root(id) as rid
    from t_location t
    start with t.name = '深圳市'
  connect by prior t.pid = t.id
  order by level desc;
)
--查找所有结点的路由,出现问题,三个结点的,排序错误,出现'华南区 深圳市 广东省'这样的情况
select rid,replace(wm_concat(name),',',' ') as addr from(
  select t.name,connect_by_root(id) as rid
    from t_location t
  connect by prior t.pid = t.id
  order by level desc
)
group by rid;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值