SQL优化:SQL中使⽤withas语法
解释:
WITH AS短语,也叫做⼦查询部分,定义⼀个SQL⽚段后,该SQL⽚断可以被整个SQL语句所⽤到。有的时候,with as是为了提⾼SQL语句的可读性,减少嵌套冗余。
⽰例:
语法: with temp名字 as 查询语句,temp名字1 as 查询语句,...
例⼦:
with eg  as ( select * from users)
select * from eg
执⾏顺序:先执⾏as⾥⾯的,存进⼀个临时表中
场景
1. 将sql语句中的频繁重复查询的语句使⽤with as语法,提⾼查询效率
2. 递归查询
//第⼀种写法
with cte(id,name,parent_id) as (select id,name,parent_id from menuTable where parent_id=0 union all select id,name,parent_id from menuTable where cte.id=parent_id)
select id,name,parent_id from cte
//第⼆种写法
with cte(id,name,parent_id) as (select id,name,parent_id from menuTable where parent_id=0 union all select id,name,parent_id from menuTable aa inner join bb on aa.id=bb.parent_id) select id,name,parent_id from cte
注意
1. with as 后⾯必须使⽤该 with,不然会失效
2. with 可在as内部使⽤
sql语句优化方式
3. with 语句只能有⼀个with ,可以有多个as, 使⽤英⽂逗号隔开

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。