设为首页 加入收藏

TOP

sql union all 语法
2011-06-12 21:40:32 来源: 作者: 【 】 浏览:357次 评论:0

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 语法更多相关文章

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇mysql sql查询优化方法 下一篇sql join on联合查询实例

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位