一、子查詢
1、子查詢(subquery):嵌套在其他查詢中的查詢。
例如:select user_id from usertable where mobile_no in (select mobile_no from mobile where mobile_id = '10086');
這條SQL語句中,括號內為從mobile表匯總檢索mobile_id為10086的所有行中的mobile_no列,括號外為從user_table表中檢索mobile_id為10086的所有行中的user_id列;
PS:select語句中,子查詢總是從內向外處理(實際上,MySQL執行了2個select操作),where子句中使用子查詢,必須保證select語句具有與where子句中相同數目的列;
子查詢一般與in操作符結合使用,但也可用於測試等於(=)、不等於(<>)等。
格式化SQL:包含子查詢的select語句一般相較來說閱讀和調試更為不方便,特別是它比較復雜的情況下,因此把子查詢分解為多行並且適當縮進,能極大的簡化子查詢的使用。
2、使用計算字段使用子查詢
例如:select user_name,user_id,(select count(*))
from orders where orders_cust_id = usertable_user_id)
as orders
from usertable
order by user_name;
這條SQL語句對usertable表中每個用戶返回3列:user_name,user_id和orders,orders是一個計算字段,由圓括號內的子查詢建立,它對檢索出的每個用戶執行一次,
子查詢中where子句它使用了完全限定表名,它告訴SQL比較orders表和usertable表中的user_id列。
相關子查詢(correlated subquery):涉及外部查詢的子查詢(任何時候只要列名可能存在多叉性,就必須使用這種語法[表名和列名有一個句點分隔])。
PS:使用子查詢建立查詢的最可靠方法是逐漸進行(首先建立最內層的查詢,確認后用硬編碼數據建立外層查詢,由內到外)
二、組合查詢
MySQL允許執行多個查詢(多條select語句),並將結果作為單個查詢結果集返回,這些組合查詢稱為並(union)或復合查詢(compound query)。
以下兩種基本情況,需要使用組合查詢:
①在單個查詢中從不同表返回類似結構的數據;
②對單個表執行多個查詢,按單個查詢返回數據;
1、union
union可將多條select語句的結果組合成單個結果集,例子如下
select user_id, mobile_id, mobile_num
from mobiletables
where mobile_num = 10086
union
select user_id, mobile_id, mobile_num
from mobuletables
where user_id in (10000,10010);
這條SQL語句中,union指示MySQL執行兩條select語句,並把輸出組合成單個查詢結果集。
union使用規則:
①union必須由兩條或以上的select語句組成,語句之間用關鍵字union分隔;
②union中每個查詢必須包含相同的列、表達或聚集函數(各個列不需要以相同的次序列出);
③列數據類型必須兼容:類型不用完全相同,但必須是DBMS可以隱含的轉換類型;
④union自動從查詢結果集中去除重復的行(這是union的默認行為,如果想返回所有匹配行,可使用union all)
2、union all
union自動從查詢結果集中去除重復的行,如果想返回所有匹配行,可使用union all;例子如下:
select user_id, mobile_id, mobile_num
from mobiletables
where mobile_num = 10086
union all
select user_id, mobile_id, mobile_num
from mobuletables
where user_id in (10000,10010);
union和where的區別:
union幾乎可以完成與多個where條件相同的工作。union all為union的一種形式,它完成where子句完成不了的工作(如果需要每個條件匹配行全部出現,則必須使用union all)。
3、對組合查詢結果排序
select語句的輸出用order by子句排序,在用union組合查詢時,只能使用一條order by子句,它必須出現在最后一條select語句之后。
select user_id, mobile_id, mobile_num
from mobiletables
where mobile_num = 10086
union all
select user_id, mobile_id, mobile_num
from mobuletables
where user_id in (10000,10010)
order by user_id, mobile_num;
MySQL將用它來排序所有的select語句返回的所有結果。