SQL优化:SQL中使用with as 语法


  • 解释:

    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内部使用
  3. with 语句只能有一个with ,可以有多个as, 使用英文逗号隔开