萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> sql union all 語法

sql union all 語法

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

copyright © 萬盛學電腦網 all rights reserved