- 組合查詢也叫並,複合查詢。
有多個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