一個查詢寂汇,通常就是一個select語句,但如果一個select查詢語句中,又嵌套了select查詢語句冤议,其后者就稱為"子查詢"斟薇,前者就是"主查詢"。
語法
selelct 字段或表達式或(子查詢1) [as 別名] from 表名或(子查詢2) where 字段或表達式或(子查詢3) 的條件判斷
其中每個位置所放置的子查詢結(jié)果應(yīng)該符合該位置的數(shù)據(jù)要求恕酸,子查詢1應(yīng)該是一個數(shù)據(jù)結(jié)果堪滨,子查詢2可以是任意結(jié)果,此位置的查詢結(jié)果通產(chǎn)作為數(shù)據(jù)源蕊温,可以設(shè)置一個別名袱箱,自查詢3可以是一個數(shù)據(jù)或一列數(shù)據(jù)甚至是一行數(shù)據(jù)。
子查詢按結(jié)果分類
- 表子查詢 : 一個子查詢返回的結(jié)果理論上是“多行多列”的時候义矛。此時可以當做一個“表”來使用发笔,通常是放在from后面。
- 行字查詢 : 一個子查詢返回的結(jié)果理論上是“一行多列”的時候凉翻。此時可以當做一個“行”來使用了讨,通常放在“行比較語法”中。
- 列子查詢 : 一個子查詢返回的結(jié)果理論上是“多行一列”的時候制轰。此時可以當做“多個值”使用前计,類似這種:(5, 17, 8, 22)。
- 標量子查詢:一個子查詢返回的結(jié)果理論上是“一行一列”的時候垃杖。此時可以當做“一個值”使用男杈,類似這種:select 5 as c1; 或select ...where a = 17,或select ... where b > 8;
子查詢按使用場合分
- 作為主查詢的結(jié)果數(shù)據(jù):select c1,(select f1 from tab2) as f11 from tab1; #這里子查詢應(yīng)該只有一個數(shù)據(jù)(一行一列调俘,標量子查詢)
- 作為主查詢的條件數(shù)據(jù):select c1 from tab1 where c1 in (select f1 from tab2); #這里子查詢可以是多個數(shù)據(jù)(多行一列伶棒,列子查詢,以及標量子查詢彩库,實際上行子查詢也可能,但極少)
- 作為主查詢的來源數(shù)據(jù):select c1 from (select f1 as c1, f2 from tab2) as t2; #這里子查詢可以是任意查詢結(jié)果(表子查詢)侧巨。
常見子查詢和相關(guān)關(guān)鍵字
數(shù)據(jù)表1鞭达,下面案例會用到
數(shù)據(jù)表2,下面案例會用到
- 比較運算符中使用子查詢:判斷字段的值是否滿足比較結(jié)果畴蹭,形式一般寫為:操作數(shù) 比較運算符 (標量子查詢)。
案例:找出所有大于平均價的商品
//步驟:
//1.找平均價
select avg(price) as avg_price from product;
//2.找商品
select * from product where price > xxxxx;
//合并起來一起寫
select * from product where price >(select avg(price) as avg_price from product);
- 使用in子查詢:表示該操作數(shù)(字段值)等于該子查詢的任意一個值就滿足條件
案例:找出所有帶"電"字的類別的ID
//1.找出所有帶"電"字的類別ID
select protype_id from product_type where protype_name like '%電';
//2.根據(jù)結(jié)果找出這些類別的產(chǎn)品
select * from product where protype id in xxx
//使用in子查詢
select * from product where protype id in
(
select protype_id from product_type where protype_name like '%電'
);
- 使用any子查詢:表示該操作數(shù)的值跟列子查詢的任意一個值滿足條件就行 叨襟。
案例:找出所有帶"電"字的類別的產(chǎn)品
select * from product where protype_id=any
(
select protype_id from product_type where protype_name like '%電%'
);
- 使用all子查詢:表示該操作數(shù)的值必須跟列子查詢的所有值都滿足給定的比較運算,才算滿足了條件。
案例:找出產(chǎn)品表中的價格最高得產(chǎn)品
//法1:使用all子查詢
select * from product where price>=all
(
select price from product
);
//法2:
select * from product where price =
(
select price from product
);
- 使用exists的子查詢:如果該子查詢有結(jié)果數(shù)據(jù)(無論什么數(shù)據(jù)梳玫,只要大于等于1行)爹梁,則為true,否則為false
案例:找出具有在售商品的那些類別
select * from product_type where exists
(
select * from product where product.protype_id=product_type.protype_id
);
- 使用not exists的子查詢:與exists的子查詢相反
注意:使用exists或not exists子查詢,如果涉及到2個表提澎,其內(nèi)部其實會自動進行"連接查詢"姚垃,且其邏輯過程較為負責,而且不明確盼忌。無法自行設(shè)置积糯。