sql union all 文法

來源:互聯網
上載者:User

sql union all 文法
表名:table
欄位:id  username ytime
需要實現的結果是:
查詢1:
   select top 5 * from table where id>20 order by id asc
查詢2:
   select top 5 * from table where id<20 order by id desc
並且再將查詢1和查詢2之和,再按照id的倒序。原以為:查詢2好辦,本來就倒序了,並且都小於20,所以這個不需要改動的。現在需要再將查詢1進行一次排序就行了。
於是寫了一個sql語句:
select * from (select top 5 * from table where id>20 order by id asc) order by id desc
union all
select top 5 * from table where id>20 order by id asc
啟動並執行結果居然是:id>20的那5條記錄沒有倒序。

必須換種寫法了:
select * from (select top 5 * from table where id>20 order by id asc
union all
select top 5 * from table where id>20 order by id asc) order by id desc

詳細說明

union
union 命令用於從兩個表中選取相關的資訊,很類似 join 命令。不過,當使用 union 命令時,所有被選取的列的資料類型應該是相同的。

注釋:如使用 union,那麼只有不同的值會被選取。

sql statement 1 union sql statement 2
下面的例子中使用的原始表:
employees_china:
e_id e_name
01 zhang, hua
02 wang, wei
03 carter, thomas
04 yang, ming

employees_usa:
e_id e_name
01 adams, john
02 bush, george
03 carter, thomas
04 gates, bill

使用 union 命令
執行個體
列出所有在中國和美國的不同的僱員名:

select e_name from employees_china union select e_name from employees_usa
結果
e_name
zhang, hua
wang, wei
carter, thomas
yang, ming
adams, john
bush, george
gates, bill

注釋:這個命令無法列出在中國和美國的所有僱員。在上面的例子中,我們有兩個名字相同的僱員,他們當中只有一個人被列出來了。union 命令只會選取不同的值。

union all
union all 命令和 union 命令幾乎是等效的,不過 union all 命令會列出所有的值。

sql statement 1 union all sql statement 2
使用 union all 命令
執行個體:
列出在中國和美國的所有的僱員:

select e_name from employees_china union all select e_name from employees_usa
結果
e_name
zhang, hua
wang, wei
carter, thomas
yang, ming
adams, john
bush, george
carter, thomas
gates, bill

聯繫我們

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