mysql常用查詢:group by,左串連,子查詢,having where

來源:互聯網
上載者:User

前幾天去了兩個比較牛的互連網公司面試,在sql這塊都遇到問題了,哎,可惜呀,先把簡單的梳理一下

成績表 score



1、group by 使用

按某一個維度進行分組

例如:

求每個同學的總分

SELECT student,SUM(score) FROM score GROUP BY student

求每個同學的平均分

SELECT student,AVG(score) FROM score GROUP BY student

也可以按照 班級,課程 來求


2、having 與 where的區別

having與where類似,可以篩選資料,where後的運算式怎麼寫,having後就怎麼寫
  • where針對錶中的列發揮作用,查詢資料
  • having對查詢結果中的列發揮作用,篩選資料
例如:

查出掛了兩門及以上的學生

SELECT student,SUM(score<60)as gk FROM score GROUP BY student HAVING gk>1

3、子查詢

(1)where子查詢

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

求比每門課程平均分低的學生

SELECT student ,course, score 
FROM score ,(SELECT course AS a_course,AVG( score)AS a_score FROM score GROUP BY course) AS avg_score
WHERE course = a_course AND score<a_score


先寫到這吧

可以參考

http://www.cnblogs.com/rollenholt/archive/2012/05/15/2502551.html




聯繫我們

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