我有一个包含分层元素的表
表:
A B P1 - P2 P1 C1 P2 C2 P2
B是来自同一个表的外键
查询是:
SELECT level niveau, A from table parent, table child START WITH A IN ( 'P0','P1','C2') CONNECT BY PRIOR A= B
结果
1 P1 1 P2 2 C1 2 C2 1 C2
为什么会出现“2 C2”?
尽管不正确,但期望的结果是:
1 P1 1 P2 2 C1 1 C2
最佳答案
首先评估
Connect by
条件,然后评估start with
。在您的情况下,C2 既是 P2 的子级,又是层次结构的根。这就是它在您的结果中出现两次的原因。
Oracle processes hierarchical queries as follows:
A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.
The CONNECT BY condition is evaluated.
Any remaining WHERE clause predicates are evaluated.
Oracle then uses the information from these evaluations to form the hierarchy using the following steps:
Oracle selects the root row(s) of the hierarchy--those rows that satisfy the START WITH condition.
Oracle selects the child rows of each root row. Each child row must satisfy the condition of the CONNECT BY condition with respect to one of the root rows.
Oracle selects successive generations of child rows. Oracle first selects the children of the rows returned in step 2, and then the children of those children, and so on. Oracle always selects children by evaluating the CONNECT BY condition with respect to a current parent row.
If the query contains a WHERE clause without a join, then Oracle eliminates all rows from the hierarchy that do not satisfy the condition of the WHERE clause. Oracle evaluates this condition for each row individually, rather than removing all the children of a row that does not satisfy the condition.
Oracle returns the rows in the order shown in Figure 9-1. In the diagram, children appear below their parents. For an explanation of hierarchical trees,
关于oracle - 通过先前的预言机连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12746094/