龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 数据库类 > MySQL 技术 >

sql union all 语法

时间:2011-03-14 23:24来源:未知 作者:admin 点击:
分享到:
sql union all 语法 表名:table 字段:id username ytime 需要实现的结果是: 查询1: select top 5 * from table where id20 order by id asc 查询2: select top 5 * from table where id20 order by id desc 并且再将查询1和

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

sql union all 语法更多相关文章

精彩图集

赞助商链接