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

在這裏插入圖片描述

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