SQL中递归cte方法的控制流程是怎样的?
What is the flow of control of recursive cte methods in SQL?
我有一个问题需要解决 a question:
with recursive cte as(
select employee_id from employees where manager_id = 1 and employee_id != 1
union all
select a.employee_id from employees a inner join cte b on b.employee_id=a.manager_id)
select employee_id from cte
我阅读了文档并了解到第一行是 anchor member
,第二行连接结果集,第三行是引用 cte 的子查询,因此是递归。
我不明白的是控制流程。例如,声明了一个名为 cte
的 cte,我们 运行 一个 select 查询(锚),然后我们执行一个 union all 与另一个递归调用这个 cte 的结果集。
文档中指出,一旦结果集为空,递归就会终止。我无法理解递归将在流程的哪一步终止。
It is stated in the documentation that the recursion terminates once the result set is empty. I am not able to understand at what step of the flow will the recurion terminate.
让我们看一下 CTE 的递归部分:
select a.employee_id
from employees a
inner join cte b on b.employee_id = a.manager_id
这个return什么时候没有行?当没有manager_id
等于cte
的employee_id
的员工时。
基本上,查询遍历层次结构:在每一步,它都会带来当前员工的 managees。当当前员工没有管理任何员工时,递归部分返回空,递归停止。
我有一个问题需要解决 a question:
with recursive cte as(
select employee_id from employees where manager_id = 1 and employee_id != 1
union all
select a.employee_id from employees a inner join cte b on b.employee_id=a.manager_id)
select employee_id from cte
我阅读了文档并了解到第一行是 anchor member
,第二行连接结果集,第三行是引用 cte 的子查询,因此是递归。
我不明白的是控制流程。例如,声明了一个名为 cte
的 cte,我们 运行 一个 select 查询(锚),然后我们执行一个 union all 与另一个递归调用这个 cte 的结果集。
文档中指出,一旦结果集为空,递归就会终止。我无法理解递归将在流程的哪一步终止。
It is stated in the documentation that the recursion terminates once the result set is empty. I am not able to understand at what step of the flow will the recurion terminate.
让我们看一下 CTE 的递归部分:
select a.employee_id
from employees a
inner join cte b on b.employee_id = a.manager_id
这个return什么时候没有行?当没有manager_id
等于cte
的employee_id
的员工时。
基本上,查询遍历层次结构:在每一步,它都会带来当前员工的 managees。当当前员工没有管理任何员工时,递归部分返回空,递归停止。