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, 使用英文逗號隔開

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM