是否可以在Oracle SQL中仅使用联接而不使用connect by子句编写分层查询
给定:是否可以在Oracle SQL中仅使用联接而不使用connect by子句编写分层查询,sql,oracle,join,hierarchical-query,Sql,Oracle,Join,Hierarchical Query,给定: ID : Parent 45 : 22 22 : 1 1 : null object\u表 ------------ 身份证件 父母亲 样本数据: ID : Parent 45 : 22 22 : 1 1 : null ID:Parent 1:null 22 : 1 45 : 22 32 : 45 使用connect by子句进行查询: select * from object_table start with id = 45 connect by prior
ID : Parent
45 : 22
22 : 1
1 : null
object\u表
------------
身份证件
父母亲
样本数据:
ID : Parent
45 : 22
22 : 1
1 : null
ID:Parent
1:null
22 : 1
45 : 22
32 : 45
使用connect by子句进行查询:
select * from object_table
start with id = 45
connect by prior parent = id;
结果:
ID : Parent
45 : 22
22 : 1
1 : null
是否可以编写一个查询,只使用连接而不使用CONNECTBY子句来给出相同的结果 是的,自从Oracle 11g第2版以来,您可以使用递归CTE,而不是旧式的分层查询。此外,递归CTE更灵活,因为它们允许您遍历任何类型的图形 例如:
create table t (
id number(6),
parent number(6)
);
insert into t (id, parent) values (1, null);
insert into t (id, parent) values (22, 1);
insert into t (id, parent) values (45, 22);
insert into t (id, parent) values (32, 45);
with n (id, parent, lvl) as (
select id, parent, 1 from t where id = 45
union all
select t.id, t.parent, n.lvl + 1
from n
join t on t.id = n.parent
)
select * from n order by lvl
结果:
ID PARENT LVL
-- ------ ---
45 22 1
22 1 2
1 <null> 3
ID父级LVL
-- ------ ---
45 22 1
22 1 2
1 3
是的,自Oracle 11g第2版以来,您可以使用递归CTE,而不是旧式的分层查询。此外,递归CTE更灵活,因为它们允许您遍历任何类型的图形
例如:
create table t (
id number(6),
parent number(6)
);
insert into t (id, parent) values (1, null);
insert into t (id, parent) values (22, 1);
insert into t (id, parent) values (45, 22);
insert into t (id, parent) values (32, 45);
with n (id, parent, lvl) as (
select id, parent, 1 from t where id = 45
union all
select t.id, t.parent, n.lvl + 1
from n
join t on t.id = n.parent
)
select * from n order by lvl
结果:
ID PARENT LVL
-- ------ ---
45 22 1
22 1 2
1 <null> 3
ID父级LVL
-- ------ ---
45 22 1
22 1 2
1 3
是的,由于Oracle 11,您可以使用标准的SQL递归CTE。是的,但是您需要为您遍历的每个“级别”单独创建一个join
。你需要提前知道它的深度。这可能有助于解释为什么你要避免使用某个特定的功能。很多问题都是以“在不使用feature X的情况下如何做到这一点”开始的。是的,因为Oracle 11可以使用标准SQL递归CTE。是的,但是对于您遍历的每个“级别”,您需要一个单独的join
。你需要提前知道它的深度。这可能有助于解释为什么你要避免使用某个特定的功能。以“不使用功能X我如何做到这一点”开头的许多问题如下所示。