oraclesql中的分层数据

oraclesql中的分层数据,sql,oracle,group-by,Sql,Oracle,Group By,我在Oracle SQL中有这样的tbl_父级,示例数据如下所示: Id(primary key) parentid childid 1 1 2 2 1 3 3 2 1 4 3 1 -- This row is wrong 在上表中,有些行插入错误,例如,如果

我在Oracle SQL中有这样的tbl_父级,示例数据如下所示:

 Id(primary key)   parentid   childid

  1                 1           2
  2                 1           3
  3                 2           1
  4                 3           1  -- This row is wrong

在上表中,有些行插入错误,例如,如果
parent\u id
1有
child\u id
3,那么
parent\u id
3不应该有
child\u id
1,因为3已经是1的子代,所以不能是父代,我有5000多行,希望找到这些不正确的行,有什么帮助吗?

最大的
最小的
函数可以用作

select least(parentid,childid) as least_par_chi_id,
       greatest(parentid,childid) as greatest_par_chi_id
  from tab
 group by greatest(parentid,childid), least(parentid,childid)
having count(*)>1;

基本上,您是在表中查找周期

Oracle在分层查询中识别周期的功能是

此查询显示导致循环的所有节点-列
为\u cycle=1

select tbl.* ,
CONNECT_BY_ISCYCLE  is_Cycle, 
SYS_CONNECT_BY_PATH(childid, '/') path
from tbl
CONNECT BY NOCYCLE PRIOR childid = parentid
对于您的数据,结果是

  PARENTID    CHILDID   IS_CYCLE PATH     
---------- ---------- ---------- ----------
         1          2          0 /2         
         2          1          1 /2/1       
         1          3          1 /2/1/3     
         1          3          0 /3         
         3          1          1 /3/1       
         1          2          1 /3/1/2     
         2          1          0 /1         
         1          2          1 /1/2       
         1          3          1 /1/3       
         3          1          0 /1         
         1          2          1 /1/2       
         1          3          1 /1/3 
注意:每个周期都在几个地方被识别,因此您会得到一些冗余数据

这种方法的优点是,它也适用于更长的周期(简单的分组方法失败)

长度为3的循环示例:

create table tbl as
select 1 parentid, 2   childid from dual union all
select 2 parentid, 3   childid from dual union all
select 3 parentid, 1   childid from dual;

  PARENTID    CHILDID   IS_CYCLE PATH     
---------- ---------- ---------- ----------
         1          2          0 /2         
         2          3          0 /2/3       
         3          1          1 /2/3/1     
         2          3          0 /3         
         3          1          0 /3/1       
         1          2          1 /3/1/2     
         3          1          0 /1         
         1          2          0 /1/2       
         2          3          1 /1/2/3 

同样适用于2-1和1-2。。。