oracle层次结构查询错误ORA-01436:用户数据中的CONNECT BY循环

时间:2018-08-02 15:03:56

标签: sql oracle oracle11g

我有一个名为 abc 的表 列和数据如下:-

a    b    c
------------
ab   1    2
bc   2    3
cd   3    4
de   4    5

也许有类似循环的数据-

ef   5    1

我希望输出为:-

A   b    d
------------
ab  1    5/4/3/2/1
bc  2     5/4/3/2
cd  3     5/4/3
de  4      5/4
ef  5       5

请帮助我找到一个查询来检索这样的数据

3 个答案:

答案 0 :(得分:0)

您可以将listaggselect level from dual connect by level <= ?语句一起使用,并且不需要列c(并且列a仅对于 output 才需要) ,如以下例程所示:

create table tab( a varchar2(2), b int );

insert all
       into tab values('ab',1) 
       into tab values('bc',2)
       into tab values('cd',3)
       into tab values('de',4)
       into tab values('ef',5)
select * from dual;

select a, b, 
      ( select listagg(6-level,'/') within group (order by level)
          from dual
        connect by level <= 6-b ) as d
  from tab t;

SQL Fiddle Demo

答案 1 :(得分:0)

with
  my_data(a,b,c) AS (
    select 'ab', 1, 2 from dual union all
    select 'bc', 2, 3 from dual union all
    select 'cd', 3, 4 from dual union all
    select 'de', 4, 5 from dual union all
    select 'ea', 5, 1 from dual   
  )  
  select a, b, sys_connect_by_path(b, '/') d
    from my_data t
  connect by nocycle c = prior b
    start with c = 1
    order by a;

答案 2 :(得分:0)

您可以使用带有CYCLE子句的递归CTE来避免循环数据

WITH cte(a, b, c, d) AS
  ( SELECT a,
           b,
           c,
           to_char(b) AS d
    FROM abc
   WHERE c = 1
   UNION ALL SELECT t.a,
                    t.b,
                    t.c,
                    cte.d ||'/'||t.b
    FROM abc t
   JOIN cte ON (cte.b = t.c) ) 
CYCLE b SET CYCLE TO 1 DEFAULT 0
SELECT a,
       b,
       d
FROM cte
WHERE CYCLE = 0
ORDER BY b ;

Demo