码迷,mamicode.com
首页 > 数据库 > 详细

mysql经常使用查询:group by,左连接,子查询,having where

时间:2017-04-28 13:35:41      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:src   html   互联网   表达   com   sum   logs   公司   archive   

前几天去了两个比較牛的互联网公司面试。在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




mysql经常使用查询:group by,左连接,子查询,having where

标签:src   html   互联网   表达   com   sum   logs   公司   archive   

原文地址:http://www.cnblogs.com/claireyuancy/p/6780915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!