有没有在connect by oracle with nocycle中添加一个循环行?
Is there any to add one loop row in connect by oracle with nocycle?
就像当循环发生在顶层节点(根节点直接连接回根节点)时 Oracle 继续遵循循环之外的路径一样,有没有办法在循环之间做同样的事情。
就像我有一些像下面这样的数据
create table t1 ( c1 varchar2(2), c2 varchar2(2));
insert into t1 values ('A', 'B');
insert into t1 values ('B', 'C');
insert into t1 values ('C', '**A**');
并执行以下查询:
select * from (
select distinct
connect_by_root c1 as c3,
c1,
c2
from t1
connect by nocycle c1 = prior c2
) where c3='A';
它会给我这个结果
c3 c1 c2
A A B
A B C
**A** **C** **A**
它给了我根循环值。但是如果我有如下数据。
create table t2 ( c1 varchar2(2), c2 varchar2(2));
insert into t2 values ('A', 'B');
insert into t2 values ('B', 'C');
insert into t2 values ('C', '**B**');
select * from (
select distinct
connect_by_root c1 as c3,
c1,
c2
from t2
connect by nocycle c1 = prior c2
) where c3='A';
这给了我
c3 c1 c2
A A B
A B C
但我还需要第三排,即 A C B。
所以想知道这是否可以做到?
您可以使用递归子查询分解子句:
WITH rsqfc ( c3, c1, c2 ) AS (
SELECT c1, c1, c2
FROM t2
WHERE c1 = 'A'
UNION ALL
SELECT r.c3, t.c1, t.c2
FROM t2 t
INNER JOIN rsqfc r
ON ( t.c1 = r.c2 )
)
CYCLE c1, c2 SET is_cycle TO 1 DEFAULT 0
SELECT c3, c1, c2
FROM rsqfc
WHERE is_cycle = 0;
其中,对于您的示例数据:
create table t2 ( c1, c2 ) AS
SELECT 'A', 'B' FROM DUAL UNION ALL
SELECT 'B', 'C' FROM DUAL UNION ALL
SELECT 'C', 'B' FROM DUAL;
输出:
C3 | C1 | C2
:- | :- | :-
A | A | B
A | B | C
A | C | B
db<>fiddle here
就像当循环发生在顶层节点(根节点直接连接回根节点)时 Oracle 继续遵循循环之外的路径一样,有没有办法在循环之间做同样的事情。 就像我有一些像下面这样的数据
create table t1 ( c1 varchar2(2), c2 varchar2(2));
insert into t1 values ('A', 'B');
insert into t1 values ('B', 'C');
insert into t1 values ('C', '**A**');
并执行以下查询:
select * from (
select distinct
connect_by_root c1 as c3,
c1,
c2
from t1
connect by nocycle c1 = prior c2
) where c3='A';
它会给我这个结果
c3 c1 c2
A A B
A B C
**A** **C** **A**
它给了我根循环值。但是如果我有如下数据。
create table t2 ( c1 varchar2(2), c2 varchar2(2));
insert into t2 values ('A', 'B');
insert into t2 values ('B', 'C');
insert into t2 values ('C', '**B**');
select * from (
select distinct
connect_by_root c1 as c3,
c1,
c2
from t2
connect by nocycle c1 = prior c2
) where c3='A';
这给了我
c3 c1 c2
A A B
A B C
但我还需要第三排,即 A C B。 所以想知道这是否可以做到?
您可以使用递归子查询分解子句:
WITH rsqfc ( c3, c1, c2 ) AS (
SELECT c1, c1, c2
FROM t2
WHERE c1 = 'A'
UNION ALL
SELECT r.c3, t.c1, t.c2
FROM t2 t
INNER JOIN rsqfc r
ON ( t.c1 = r.c2 )
)
CYCLE c1, c2 SET is_cycle TO 1 DEFAULT 0
SELECT c3, c1, c2
FROM rsqfc
WHERE is_cycle = 0;
其中,对于您的示例数据:
create table t2 ( c1, c2 ) AS
SELECT 'A', 'B' FROM DUAL UNION ALL
SELECT 'B', 'C' FROM DUAL UNION ALL
SELECT 'C', 'B' FROM DUAL;
输出:
C3 | C1 | C2 :- | :- | :- A | A | B A | B | C A | C | B
db<>fiddle here