百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> sql union all 语法
分享文章到:

sql union all 语法

发布时间:01/15 来源: 浏览: 关键词:

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

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有4人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板