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;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值