9-oracle_union和union all
Union 是对结果集的并集操作,会要求 2 个集合是要有相同的字段和类型。
Union :对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序
Union all :对两个结果集进行并集操作,包括重复行,不进行排序
Union: 我们对同一个表做 2 次查询,查询的结果并没有出现重复的 2 条出现:
select user_no, dept_code, sales_amt
from t_sales
union
select user_no, dept_code, sales_amt
from t_sales;
哪这条语句的默认规则排序是怎样排序的呢?是按我们查询字段的顺序进行升序排序的。上面则是按 user_no,dept_code,sales_amt 进行排序的,为了证明我们所说的,我们换下查询字段的顺序,按 sales_amt,user_no,dept_code 查询:
select sales_amt, user_no, dept_code
from t_sales
union
select sales_amt, user_no, dept_code
from t_sales;
结果很明显是按我们所说的查询字段先后顺序后的升序排序的。
Union all :对 2 个查询的集合做并集,对重复的行不做处理:
select user_no, dept_code, sales_amt
from t_sales
union all
select user_no, dept_code, sales_amt
from t_sales;
我们对表做了 2 次查询,所以出现了每条记录有 2 条。并且结果数据集也是乱序的。其实这个是我们的表面现象,在返回的结果集也是有顺序的:先返回第一个查询的结果,返回的顺序是按记录的插入顺序来的,再返回第二个查询的结果集,返回的顺序也是按记录的插入顺序来的。可以通过如下 2 个脚本来验证:
select user_no, dept_code, sales_amt
from t_sales a
where a.sales_amt <= 5000
union all
select user_no, dept_code, sales_amt
from t_sales a
where a.sales_amt > 3000 ;
第一个查询返回的是蓝色的记录 3 条。
select user_no, dept_code, sales_amt
from t_sales a
where a.sales_amt > 3000
union all
select user_no, dept_code, sales_amt
from t_sales a
where a.sales_amt <= 5000 ;
第一个查询返回的蓝色记录是 6 条,与上个脚本的第 2 个查询返回的记录一样,所以我们的 uinion all 返回也是有顺序的,先按查询脚本,再按单个脚本的记录插入顺序。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/31535951/viewspace-2641328/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/31535951/viewspace-2641328/
- 点赞
- 收藏
- 分享
- 文章举报
- ORACLE进阶(十二)union(all)学习
- Oracle 中 union 和union all 的简单使用说明
- oracle 横表转纵表 cube函数及union all用法
- ORACLE的UNION和UNION ALL 的用法1
- Oracle的Union、Union_All、Intersect、Minus用法---小笔记
- oracle 10g 行列转换 通过decode和union all 实现
- Oracle sql union all
- Oracle 之Union all
- oracle union all
- Oracle Union All 排序
- oracle union union all intersect minus
- Oracle union all和order by一起使用
- ORACLE union all 与 union 的区别
- oracle union union all intersect minus的含义及区别
- Oracle Union/Union All/Intersect/Minus区别
- Oracle union union all
- Oracle union all和order by一起使用
- oracle union union all 区别
- Oracle UNION ALL/UNION/INTERSECT/MINUS
- Oracle Union Union All 对查询结果集操作