SQL必知必会 第14课 组合查询
14.1 组合查询
SQL允许执行多个查询(多条SELECT语句),并将结果作为一个查询结果集返回。这些组合查询通常称为并或复合查询。
有两种情况需要使用组合查询:
- 在一个查询中从不同的表返回结构数据;
- 对一个表执行多个查询,按一个查询返回数据。
14.2 创建组合查询
可用UNION操作符来组合数条SQL查询。
UNION
在每条select语句之间放上关键字UNION即可。
# 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';
UNION 规则
- UNION必须由两条或两条以上的SELECT语句组成,语句之间用关键字UNION分隔
- UNION 中的每个查询必须包括相同的列、表达式或聚集函数
- 列数据类型必须兼容:类型不必完全相同,但必须是DBMS可以隐含转换的类型
包含或取消重复的行
UNION从查询结果集中自动去除了重复的行。但如果不想去除(返回所有匹配行),可使用UNION ALL 而不是 UNION
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';
对组合查询结果排序
在用UNION组合查询时,只能使用一条ORDER BY子句,必须位于最后一条SELECT语句之后。
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, cust_contact;
还没有评论,来说两句吧...