手记

【学习打卡】第11天 MySQL8.0版本新特性

课程章节:第三章第3节 优化器索引、第四章通用表达式

主讲老师:董旭阳(Tony.Dong)

课程内容
一、函数索引
二、通用表达式CTE介绍,递归和非递归举例说明

课程收获
通用表表达式CTE,with字句的写法,

非递归:
派生表:select * from (select 1) as dt;
通用表达式写法:with cte as (select 1) select * from  cte;
如定义多个表达式,写法:a1,a2,a3.....
with a1 as (select 1),a2 as (...),a3 as ....

递归(recursive):

通用表达式写法:with recursive cte(n) as (select 1 union all select n+1 from cte where n<20) select * from cte;   ----n<20 代表递归条件

例子:员工表,存在上下级关系,打印员工表及其上下级关系:
错误写法:
with recursive employee_path(id) as(select id,name,manager_id union all select id,name,manager_id from employees where id=manager_id ) select * from employees

正确写法
with recursive employee_path(id,name,path) as(select id,name,cast(id as char(200)) from enployees where  manager_id is null union all select e.id,e.name,concat(ep.path,',',e.id) from employees_paths as ep join employees as e on ep.id=e.manager_id ) select * from employee_paths order by path;

老师说可以把cte理解为一个变量,只不过这个变量是一张表,我觉得更类似视图。


0人推荐
随时随地看视频
慕课网APP