《SQL必知必会》--组合查询

第14课 组合查询

本课讲述如何利用UNION操作符将多条SELECT语句组成一个结果集。

多数SQL查询只含从一个或多个表中返回数据的单条SELECT语句。但是SQL也允许执行多个查询(多条SELECT语句),并将结果作为一个查询结果集返回。

如下示例一

1
2
3
4
5
6
7
8
9
输入:
select cust_name, cust_contact, cust_email
from customers
where cust_state IN ('IL','IN','MI')
union
select cust_name, cust_contact, cust_email
from customers
where cust_name = 'Fun4All'
order by cust_name;
1
2
3
4
5
6
7
输出:
cust_name cust_contact cust_email
--------------------------------------------------
Fun4All Jim Jones jjones@fun4all.com
Fun4All Denise L. Stephens dstephens@fun4all.com
The Toy Store Kim Howard
Village Toys John Smith sales@villagetoys.com

注意事项:

  1. 使用UNION操作符时,每条SELECT指令必须包含相同的列名、表达式或聚集函数;
  2. 可以使用UNION进行多个SELECT指令合并。但是,每条指令之间都需要使用UNION进行间隔;
  3. 使用UNION操作符且对结果进行排序时,必须只在最后一条SELECT指令的最后一行使用ORDER命令;
  4. 使用UNION操作符的效果也相当于单条SELECT指令中WHERE限定条件中的AND\OR等操作符的使用效果(见示例二);
  5. 使用UNION指令时,会默认重复记录只显示一次,若想重复记录重复显示,则可以使用UNION ALL操作符(见示例三);
  6. 在简单的例子中,或许UNION操作符的作用尚且不如直接使用WHERE子句更简洁。但是对于复杂的过滤条件,或者从多个表中检索数据的情形,使用UNION可能会使处理更简单。

示例二

1
2
3
4
5
6
输入:
select cust_name, cust_contact, cust_email
from customers
where cust_state IN ('IL','IN','MI')
or cust_name = 'Fun4All'
order by cust_name;
1
2
3
4
5
6
7
输出:
cust_name cust_contact cust_email
--------------------------------------------------
Fun4All Jim Jones jjones@fun4all.com
Fun4All Denise L. Stephens dstephens@fun4all.com
The Toy Store Kim Howard
Village Toys John Smith sales@villagetoys.com

示例三

1
2
3
4
5
6
7
8
9
输入:
select cust_name, cust_contact, cust_email
from customers
where cust_state IN ('IL','IN','MI')
union all
select cust_name, cust_contact, cust_email
from customers
where cust_name = 'Fun4All'
order by cust_name;
1
2
3
4
5
6
7
8
输出:
cust_name cust_contact cust_email
--------------------------------------------------
Fun4All Jim Jones jjones@fun4all.com
Fun4All Jim Jones jjones@fun4all.com
Fun4All Denise L. Stephens dstephens@fun4all.com
The Toy Store Kim Howard
Village Toys John Smith sales@villagetoys.com