子查詢:
(下面的例子中cat_id表示欄目,goods_name表示商品名字,shop_price表示商品價格)
一、where型子查詢:把內層查詢的結果作為外層查詢的比較條件
例:
1、selectgoods_id,goods_name from goods where goods_id = (select max(goods_id) fromgoods);
2、查出每個欄目下最新的商品(以goods_id最大為最新)
select goods_id,cat_id,goods_name fromgoods where goods_id in (select max(goods_id) from goods group by cat_id);
//此句相當於先按cat_id分組查詢出每個欄目最新的所有good_id
然後再這個範圍內查詢出每個欄目下最新的商品
3、查出每個欄目下最貴的商品
select goods_id,cat_id,goods_name,shop_pricefrom goods where shop_price in (select max(shop_price) from goods group bycat_id);
//此句相當於先按cat_id分組查詢出每個欄目最貴的所有價格,
然後再這個範圍內查詢出每個欄目下貴的商品
二、from型子查詢:把內層的查詢結果當成暫存資料表,供外層sql重新查詢
使用from查詢出每個欄目下最新的商品(以id最大為最新)
例:
select * from (select goods_id,cat_id,goods_namefrom goods order by cat_id asc,goods_id desc) as tmp group by cat_id;
// 內層查詢:selectgoods_id,cat_id,goods_name from goods order by cat_id asc,goods_id desc;
結果如下:
整體查詢結果如下:
三、exists子查詢:把外層的查詢結果拿到內層,看內層的查詢是否成立
例:
select cat_id,cat_name from category where exists (select * from goods where goods.cat_id = category.cat_id);
外層的查詢結果放到內層使用
注釋:
五種子句是有順序要求的:where,group,having,order by,limit按這個順序寫 順序不能顛倒
列理解成變數 可以計算 select goods_id,market_price-shop_price from goods where market_price-shop_price>200;
取出的結構可以理解成一張臨時的表