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;

9-oracle_union和union all

哪这条语句的认规则排序是怎样排序的呢?是按我们查询字段的顺序进行升序排序的。上面则是按 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;

9-oracle_union和union all

结果很明显是按我们所说的查询字段先后顺序后的升序排序的。

 

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;

9-oracle_union和union all

我们对表做了 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 ;

9-oracle_union和union all

一个查询返回的是蓝色的记录 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 ;

9-oracle_union和union all

一个查询返回的蓝色记录是 6 条,与上个脚本的第 2 个查询返回的记录一样,所以我们的 uinion all 返回也是有顺序的,先按查询脚本,再按单个脚本的记录插入顺序。



相关文章

这篇文章主要介绍“hive和mysql的区别是什么”,在日常操作中...
这篇“MySQL数据库如何改名”文章的知识点大部分人都不太理解...
这篇文章主要介绍“mysql版本查询命令是什么”的相关知识,小...
本篇内容介绍了“mysql怎么修改字段的内容”的有关知识,在实...
这篇文章主要讲解了“mysql怎么删除unique约束”,文中的讲解...
今天小编给大家分享一下mysql怎么查询不为空的字段的相关知识...