mysql子查詢

來源:互聯網
上載者:User

標籤:

1、where型子查詢

(把內層查詢結果當作外層查詢的比較條件

#不用order by 來查詢最新的商品

select goods_id,goods_name from goods where goods_id = (select max(goods_id) from goods);

#取出每個欄目下最新的產品(goods_id唯一)

select cat_id,goods_id,goods_name from goods where goods_id in(select max(goods_id) from goods group by cat_id); 
2、from型子查詢

(把內層的查詢結果外層重新查詢)
#用子查詢查出掛科兩門及以上的同學的平均成績
思路:
#先查出哪些同學掛科兩門以上

select name,count(*) as gk from stu where score < 60 having gk >=2;

#以上查詢結果,我們只要名字就可以了,所以再取一次名字

select name from (select name,count(*) as gk from stu having gk >=2) as t;

#找出這些同學了,那麼再計算他們的平均分

select name,avg(score) from stu where name in (select name from (select name,count(*) as gk from stu having gk >=2) as t) group by name;
3、exists型子查詢

(把外層查詢結果拿到內層,看內層的查詢是否成立)
#查詢哪些欄目下有商品,欄目表category,商品表goods

select cat_id,cat_name from category where exists(select * from goods where goods.cat_id = category.cat_id);

mysql子查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.