SQL查询之组合查询

组合查询

SQL允许执行多个查询(多条SELECT语句),并将结果作为一个结果集返回.这些组合查询成为并(union)或复合查询(compound query)

有两种情况需要使用组合查询:
  1. 在一个查询中从不同的表返回结构数据.
  2. 对一个表执行多个查询,按一个查询返回数据.

组合查询一般使用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
*/
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值