简体   繁体   English

Oracle SQL按逻辑连接

[英]Oracle SQL Connect By Logic

Currently in one of our products we have a query with logic as explained below: 当前,在我们的一种产品中,我们具有逻辑查询,如下所示:

create table temp (emp_id varchar2(3), manager_id varchar2(3) )

Data : 资料:

E10 E20
E20 E50
E30 E50
E50 E90

Query: 查询:

select *
from Temp
    Start with EMP_ID = 'E90'
    Connect by Prior EMP_ID = MANAGER_ID and EMP_ID != MANAGER_ID
order by EMP_ID

I understand the concept of the query [& connect by] which is that we need to fetch all the children records of the employee specified including the current employee record. 我了解查询[&connect by]的概念,即我们需要获取指定员工的所有子级记录,包括当前员工记录。 I have doubts about the need of adding EMP_ID != MANAGER_ID in the end. 我对最后是否需要添加EMP_ID != MANAGER_ID表示怀疑。

The question is why was it added & in what situation will it be useful [if any]. 问题是为什么要添加它,以及在什么情况下[如果有的话]会有用。

The last condition does not apply to your data, but it is very important to avoid infinite recursion. 最后一个条件不适用于您的数据,但是避免无限递归非常重要。

To illustrate this point, consider what would happen if you added another line to your table: 为了说明这一点,请考虑如果在表中添加另一行会发生什么情况:

E40 E40

If you start with E40 instead of E90 , Oracle would spin into an infinite recursion without EMP_ID != MANAGER_ID condition, because E40 would connect back to E40 . 如果以E40而不是E90开头,则Oracle会陷入无EMP_ID != MANAGER_ID条件的无限递归,因为E40将连接回E40

Note that a better approach to writing this query is to use NOCYCLE option instead of coding in an explicit check: 请注意,编写此查询的更好方法是使用NOCYCLE选项,而不是在显式检查中进行编码:

SELECT *
FROM Temp
    START WITH EMP_ID = 'E90'
    CONNECT BY NOCYCLE PRIOR EMP_ID = MANAGER_ID
ORDER BY EMP_ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM