SQL (十三)组合查询(union操作符把多条select语句组合为一个结果集)


在这里插入图片描述
在这里插入图片描述- 组合查询也叫并,复合查询。
有多个where子句的select语句可以作为一个组合查询。

创建组合查询

在这里插入图片描述
在这里插入图片描述

示例:多条where语句和union实现达到相同效果

先看两个查询

第一个查询出Illinois、Indiana和Michigan三个州(美国)的所有顾客的三项信息

select cust_name, cust_contact, cust_email
from Customers
where cust_state in ('IL', 'IN', 'MI');

在这里插入图片描述
第二个查询查的是来自fun4all公司的所有顾客

select cust_name, cust_contact, cust_email
from Customers
where cust_name = 'Fun4All';

在这里插入图片描述

我想把两个查询结果组合起来,那应该得到4项结果,可以用where子句的or子句实现

select cust_name, cust_contact, cust_email
from Customers
where cust_name = 'Fun4All'
or cust_state in ('IL', 'IN', 'MI');

在这里插入图片描述

但是除了or子句外,还有一个办法,即用union关键字

select cust_name, cust_contact, cust_email
from Customers
where cust_state in ('IL', 'IN', 'MI') --第一个select语句不加分号
union
select cust_name, cust_contact, cust_email
from Customers
where cust_name = 'Fun4All';

在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

  • 多条where子句和union,哪个性能更好,需要自己测试一下才知道

可以看到,union自动去除了重复的行(默认行为),如果你不想让他删除重复行而是返回所有行,那就用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';

在这里插入图片描述

在这里插入图片描述

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, cust_id
from Customers
where cust_name = 'Fun4All';

在这里插入图片描述

对组合查询结果排序

在这里插入图片描述

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;

在这里插入图片描述
在这里插入图片描述

我试了试,mysql根本不支持except, intersect, minus

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章