一個查詢,通常就是一個select語句,但如果一個select查詢語句中,又嵌套了select查詢語句,其后者就稱為"子查詢",前者就是"主查詢"。
語法
selelct 字段或表達式或(子查詢1) [as 別名] from 表名或(子查詢2) where 字段或表達式或(子查詢3) 的條件判斷
其中每個位置所放置的子查詢結果應該符合該位置的數據要求,子查詢1應該是一個數據結果,子查詢2可以是任意結果,此位置的查詢結果通產作為數據源,可以設置一個別名,自查詢3可以是一個數據或一列數據甚至是一行數據。
子查詢按結果分類
- 表子查詢 : 一個子查詢返回的結果理論上是“多行多列”的時候。此時可以當做一個“表”來使用,通常是放在from后面。
- 行字查詢 : 一個子查詢返回的結果理論上是“一行多列”的時候。此時可以當做一個“行”來使用,通常放在“行比較語法”中。
- 列子查詢 : 一個子查詢返回的結果理論上是“多行一列”的時候。此時可以當做“多個值”使用,類似這種:(5, 17, 8, 22)。
- 標量子查詢:一個子查詢返回的結果理論上是“一行一列”的時候。此時可以當做“一個值”使用,類似這種:select 5 as c1; 或select ...where a = 17,或select ... where b > 8;
子查詢按使用場合分
- 作為主查詢的結果數據:select c1,(select f1 from tab2) as f11 from tab1; #這里子查詢應該只有一個數據(一行一列,標量子查詢)
- 作為主查詢的條件數據:select c1 from tab1 where c1 in (select f1 from tab2); #這里子查詢可以是多個數據(多行一列,列子查詢,以及標量子查詢,實際上行子查詢也可能,但極少)
- 作為主查詢的來源數據:select c1 from (select f1 as c1, f2 from tab2) as t2; #這里子查詢可以是任意查詢結果(表子查詢)。
常見子查詢和相關關鍵字
數據表1,下面案例會用到
數據表2,下面案例會用到
- 比較運算符中使用子查詢:判斷字段的值是否滿足比較結果,形式一般寫為:操作數 比較運算符 (標量子查詢)。
案例:找出所有大于平均價的商品
//步驟:
//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子查詢:表示該操作數(字段值)等于該子查詢的任意一個值就滿足條件
案例:找出所有帶"電"字的類別的ID
//1.找出所有帶"電"字的類別ID
select protype_id from product_type where protype_name like '%電';
//2.根據結果找出這些類別的產品
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子查詢:表示該操作數的值跟列子查詢的任意一個值滿足條件就行 。
案例:找出所有帶"電"字的類別的產品
select * from product where protype_id=any
(
select protype_id from product_type where protype_name like '%電%'
);
- 使用all子查詢:表示該操作數的值必須跟列子查詢的所有值都滿足給定的比較運算,才算滿足了條件。
案例:找出產品表中的價格最高得產品
//法1:使用all子查詢
select * from product where price>=all
(
select price from product
);
//法2:
select * from product where price =
(
select price from product
);
- 使用exists的子查詢:如果該子查詢有結果數據(無論什么數據,只要大于等于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個表,其內部其實會自動進行"連接查詢",且其邏輯過程較為負責,而且不明確。無法自行設置。