Oracle中union語句中order by用法

來源:互聯網
上載者:User

union的各個子查詢要有相同數量的列,且對應位置的列必須具有相同的資料類型;但列的名字可以不同。
只能在union的最後一個子查詢中使用order by,而這個order by是針對整個unioning後的結果集的。So:
如果unoin的幾個子查詢列名不同,如

Sql代碼 
select supplier_id, supplier_name   
from suppliers   
UNION  
select company_id, company_name   
from companies   
ORDER BY ?;  
select supplier_id, supplier_name from suppliers UNION select company_id, company_name from companies ORDER BY ?;

這裡的問號如果是company_name,則執行整個查詢會報“company_name:invalid identifier”(當然,單獨執行第二個含order by的子查詢是沒有問題的);這是因為unioning後結果集的列名是以第一個參加union的子查詢的列名為準的;order by針對的是整個unioning後的結果集。對整個查詢結果來說,無”company_name“這個欄位
如果是supplier_name,則單獨執行第二個含order by的子查詢是會報“supplier_name:invalid identifier”的,而執行整個查詢是沒有問題的,因為order by針對的是unioning後的整個結果集,而這“整個結果集”是有supplier_name這列的(以第一個union子查詢的列名作為unioning後整個結果集的列名)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.