组合查询
SQL允许执行多个查询(多条SELECT语句),并将结果作为一个结果集返回.这些组合查询成为并(union)或复合查询(compound query)
有两种情况需要使用组合查询:
- 在一个查询中从不同的表返回结构数据.
- 对一个表执行多个查询,按一个查询返回数据.
组合查询一般使用union关键字,或者多条where语句
使用多条where语句的查询,也可以看做是组合查询
-- 使用union作为组合关键字进行组合查询
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';
-- 与使用多条where语句的组合查询结果一样
select cust_name ,cust_contact,cust_email
from customers where cust_state in('IL','IN','MI')
or cust_name='Fun4All';
/*
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
*/
使用 union关键字的的规则
1.union必须由两条或者两条以上select语句组成,语句之间使用union关键字分割
2. union中每个查询必须包含相同的列,表达式,或聚集函数,各个列不需要以相同的顺序列出.
3.列数据类型必须兼容,类型不必完全相同,但必须是 DBMS可以隐含转换的类型.
使用union进行组合查询会自动去除重复的行,使用union all关键字,会显示所有匹配的行,不会去除重复.
-- 使用union all作为组合关键字进行不会去除重复的行
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';
/*
cust_name, cust_contact, cust_email
Village Toys John Smith sales@villagetoys.com
Fun4All Jim Jones jjones@fun4all.com
The Toy Store Kim Howard
Fun4All Jim Jones jjones@fun4all.com
Fun4All Denise L. Stephens dstephens@fun4all.com
*/
使用order by 对结果集进行排序.
order by语句只能出现在最后一条select 语句后面,并且只能出现一次.
-- 升序排列所有结果集
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 asc;
/*
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
*/