with recursive as实现递归

with as

with as相信大家都会用,用于创建临时表达式CTE(我理解为临时表),方便在后续代码中引用它,是的代码看起来更加简洁,且逻辑更清晰。

with tmp1 as(
    select  * from table1 ...
)
,tmp2 as(
    select  * from tmp1 ...
)


INSERT OVERWRITE TABLE bigtable

select * from tmp1
union all
select * from tmp2

with recursive as

with recursive as是一个用于创建递归查询的语句。它允许你定义一个 Common Table Expression (CTE),该 CTE 可以引用自身的输出。递归 CTE 非常适合于查询具有层次结构或树状结构的数据,例如组织结构、文件系统或任何其他具有自引用关系的数据。

基本语法

with recursive cte_name (column1,column2,...) as
(
    -- 非递归的初始部分,定义了 CTE 的起点
    select ... from   
    
    union all
    
    -- 递归部分,可以引用 CTE 的别名
    select ... from cte_name 
    where ...
)
select * from cte_name;

例1:递归获得递增的序列

with recursive cte(n) as
(
    select 1
    union all
    select n+1 from cte where n<5
)
select * from cte;


结果:
n
----
1
2
3
4
5

例2:查找树形结构所有员工及其上级经理

with recursive employee_hierarchy (id,name,manager_id,path) as
(
    -- 非递归的初始部分,查找顶层经理
    select id,name,manager_id,concat(name,'/') as path 
    from  employee
    where manager_id is null
    
    union all
    
    -- 递归部分,查找顶层经理的所有下属
    select e.id,e.name,e.manager_id,concat(e.name,'/',eh.path) as path  --将当前员工添加到路径中
    from employee e
    inner join  employee_hierarchy eh on e.manager_id=eh.id
)
select * from cte_name;


employee
id  |  name  |  manager_id
100     A           null
101     A1          100
102     A2          100
103     A11         101

结果:
id  |  name  |  manager_id  |  path
100     A           null        A/
101     A1          100         A1/A
102     A2          100         A2/A
103     A11         101         A11/A1/A

你可能感兴趣的:(数据库,sql)