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返回也是有顺序的,先按查询脚本,再按单个脚本的记录插入顺序。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。