WITH cte_name (col1, col2, ...) AS (
subquery
)
SELECT * FROM cte_name;
select d.dept_name as "部门名称",
coalesce(de.emp_number,0) as "员工数量"
from department d
left join (select dept_id,
count(*) as emp_number
from employee
group by dept_id) de
on (d.dept_id = de.dept_id);
with de(dept_id, emp_number) AS (
select dept_id,
count(*) as emp_number
from employee
group by dept_id)
select d.dept_name as "部门名称",
coalesce(de.emp_number,0) as "员工数量"
from department d
left join de on (d.dept_id = de.dept_id);
with t1(n) as (
select 2
),
t2(m) as (
select n + 1
from t1
)
select t1.n, t2.m, t1.n * t2.m
from t1, t2;
n|m|t1.n * t2.m|
-|-|-----------|
2|3| 6|
with recursive t(n) as
(
select 1
union all
select n + 1 from t where n < 10
)
select n from t;
n |
--|
1|
2|
3|
4|
5|
6|
7|
8|
9|
10|
运行初始化语句,生成数字 1;
第 1 次运行递归部分,此时 n 等于 1,满足查询条件 n < 10,返回数字 2( n+1 );
第 2 次运行递归部分,此时 n 等于 2,满足查询条件 n < 10,返回数字 3( n+1 );
第 9 次运行递归部分,此时 n 等于 9,满足查询条件 n < 10,返回数字 10( n+1 );
第 10 次运行递归部分,此时 n 等于 10;由于不满足查询条件 n < 10,不返回任何结果并且结束递归;

with recursive employee_path (emp_id, emp_name, path) as
(
select emp_id, emp_name, cast(emp_name as char(1000)) as path
from employee
where manager is null
union all
select e.emp_id, e.emp_name, cast(concat(ep.path, '->', e.emp_name) as char(1000))
from employee_path ep
join employee e on ep.emp_id = e.manager
)
select *
from employee_path
order by emp_id;
select emp_id, emp_name, cast(emp_name as char(1000)) as path
from employee
where manager is null;
emp_id|emp_name|path|
------|--------|----|
1|刘备 |刘备 |
emp_id|emp_name |path |
------|---------|-----------|
1|刘备 |刘备 |
2|关羽 |刘备->关羽 |
3|张飞 |刘备->张飞 |
4|诸葛亮 |刘备->诸葛亮|
7|孙尚香 |刘备->孙尚香|
9|赵云 |刘备->赵云 |
emp_id|emp_name |path |
------|---------|-------------------|
1|刘备 |刘备 |
2|关羽 |刘备->关羽 |
3|张飞 |刘备->张飞 |
4|诸葛亮 |刘备->诸葛亮 |
5|黄忠 |刘备->诸葛亮->黄忠 |
6|魏延 |刘备->诸葛亮->魏延 |
...
25|孙乾 |刘备->关羽->法正->孙乾|
with recursive t(n) as
(
select 1
union all
select n + 1 from t -- where n < 10
)
select n from t;
ERROR 3636 (HY000): Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value.
set session cte_max_recursion_depth = 1000000;
set global cte_max_recursion_depth = 1000000;
with recursive t(n) as
(
select 1
union all
select n + 1 from t where n < 10000
)
select /*+ SET_VAR(cte_max_recursion_depth = 1M) */ n from t;
聚合函数,例如 SUM 等;
窗口函数;
GROUP BY;
ORDER BY;
DISTINCT。
原文作者:SQL编程思想;如有侵权,请联系管理员删除。