SQL語句 - MERGE INTO 、Cross/Outer Apply用法理解

來源:互聯網
上載者:User

標籤:

MERGE INTO 文法:

MERGE INTO table_name alias1
USING (table|view|sub_query) alias2
ON (join condition)
WHEN MATCHED THEN
  UPDATE table_name
   SET col1 = col_val1,
     col2 = col2_val
WHEN NOT MATCHED THEN
  INSERT (column_list) VALUES (column_values);

   

理解:

在alias2中Select出來的資料,每一條都跟alias1進行 ON (join condition)的比較,如果匹配,就進行更新的操作(Update),如果不匹配,就進行插入操作(Insert)。
因此,嚴格意義上講,"在一個同時存在Insert和Update文法的Merge語句中,總共Insert/Update的記錄數,就是Using語句中alias2的記錄數。"

 

 

Cross/Outer Apply文法:

<左表>  {cross|outer} apply <右表>

如:

select *from Customers as C cross apply    (select top 2 *     from Orders as O     where C.customerid=O.customerid     order by orderid desc) as CA

 

理解:

  它是先得出<左表>【Customers】資料,然後將<左表>裡的每一條記錄,對應條件查詢得到<右表>的n條記錄,然後進行合并得到n行記錄,最後將所有資料行返回。

     cross和outer的區別:如果對於左表的某一行記錄,右表沒有資料,那麼cross apply結果中將沒有這一行記錄,而outer apply結果則會有一條右表都為null的記錄。

 (實際過程資料庫另有最佳化)

 

SQL語句 - MERGE INTO 、Cross/Outer Apply用法理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.