msyql資料庫 子查詢__資料庫

來源:互聯網
上載者:User

子查詢:

(下面的例子中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;


取出的結構可以理解成一張臨時的表 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.