循环层次关系查询Oracle

时间:2018-06-18 18:38:46

标签: sql oracle

我想要一个查询,它会在传递一个绑定变量时从表中给出以下输出。数据库是Oracle 11g R2

 WITH X AS (SELECT 'A1'col1, 'B1' col2 FROM dual UNION 
      SELECT 'A1'col1, 'B2' col2 FROM dual UNION 
      SELECT 'A2'col1, 'B2' col2 FROM dual UNION
      SELECT 'A2'col1, 'B3' col2 FROM dual UNION 
      SELECT 'A3'col1, 'B3' col2 FROM dual UNION 
      SELECT 'A3'col1, 'B4' col2 FROM dual UNION 
      SELECT 'A2'col1, 'B4' col2 FROM dual UNION 
      SELECT 'A4'col1, 'B1' col2 FROM dual UNION 
      SELECT 'A5'col1, 'B6' col2 FROM dual UNION 
      SELECT 'A6'col1, 'B4' col2 FROM dual UNION
      SELECT 'A7'col1, 'B8' col2 FROM dual )

for Ex bind var。对于col1:p1 = A2

输出将包含除2行之外的所有行,即'A5-B6'和'A7-B8' 换句话说,在绑定变量中传递A2时,我想要涉及两个列的所有循环关系。 预期产出:

Col1  Col2
-----  ----
A1     B1
A1     B2
A2     B2
A2     B3
A2     B4
A3     B3
A3     B4
A4     B1
A6     B4

1 个答案:

答案 0 :(得分:2)

您想要所有连接的行。所以写一个递归查询。从A2开始,然后找到相关的行。

with cte(col1, col2) as
(
  select col1, col2 from x
  where 'A2' in (col1, col2)
  union all
  select x.col1, x.col2 
  from x
  join cte on x.col1 in (cte.col1, cte.col2)
           or x.col2 in (cte.col1, cte.col2)
)
cycle col1, col2 set is_cycle to 1 default 0
select distinct col1, col2
from cte
order by col1, col2;

Rextester演示:http://rextester.com/BLUOL59045