Can somebody explain use of nocycle and connect by root clauses in hierarchical queries in oracle, also when we dont use 'start with' what is the order we get the rows, i mean when we don't use 'start with' we get lot many rows, can anybody explain nocycle and connect by root(how is different than start with?) using simple emp table, Thanks for the help
2 回答
ORA-01436: CONNECT BY loop in user data
如果您的数据中有一个循环(A -> B -> A -> B ...),如果您执行分层查询,Oracle 将抛出异常。NOCYCLE
即使存在这样的循环,也指示 Oracle 返回行。
CONNECT_BY_ROOT
使您可以访问根元素,甚至是查询中的几层。使用 HR 模式:
select level, employee_id, last_name, manager_id ,
connect_by_root employee_id as root_id
from employees
connect by prior employee_id = manager_id
start with employee_id = 100
LEVEL EMPLOYEE_ID LAST_NAME MANAGER_ID ROOT_ID
---------- ----------- ------------------------- ---------- ----------
1 100 King 100
2 101 Kochhar 100 100
3 108 Greenberg 101 100
4 109 Faviet 108 100
...
在这里,您会看到我从员工 100 开始并开始寻找他的员工。操作员允许我访问 King的CONNECT_BY_ROOT
employee_id,甚至向下四级。起初我对这个操作符很困惑,认为它的意思是“通过根元素连接”什么的。把它想象成“CONNECT BY 子句的根”。
这里是关于 nocycle 在查询中的使用。
假设我们有一个简单的表,其中包含 r1 和 r2 列名以及第一行 r1=a,r2=b 和第二行 r1=b,r2=a 的值 现在我们知道a指的是b并且b指的是a。因此存在一个循环,如果我们将分层查询编写为
select r1 from table_name start with r1='a' connect by prior r2=r1;
我们通过循环错误获得连接
因此,即使存在循环,也可以使用nocycle来允许oracle 给出结果。
因此查询 select r1 from table_name start with r1='a' connect by nocycle prior r2=r1;