mysql基础二(函数,流程,分组)
1.单行函数,比如LENGTH ,ISNULL ,CONCAT 是一个值变成另一个值
SUBSTR 截取字符串,从1开始的
比如
select SUBSTR('海贼王路飞',3)
结果是:'王路飞'
2.流程控制函数case
select stu_name,score, CASE classroomId WHEN '1' then '一班' WHEN '2' then '二班' WHEN '3' then '三班' ELSE classroomId END from student
3.分组函数,是一组值编程一个值
SUM,MIN,AVG,COUNT,MAX
select MAX(score),AVG(score) from student;
MAX ,MIN,AVG,COUNT都是忽略null 值的
4.SUM,COUNT 等搭配distinct 使用
select SUM(DISTINCT score) ,SUM(score) from student;
搭配distinct 后是求不同score 的总和
5.COUNT 函数,值的是非空计数
统计行数一般都是用select COUNT(*)
也可以使用COUNT(1)
6.注意点:和分组函数一同查询的字段必须是group by 后的字段,不然没有意义
比如:
select AVG(score) ,stu_name from student;
这里的AVG(score) 查出来是一个,stu_name是多个,所以查出来没有意义
7.group by
例子:查询每个班的平均分数
select AVG(score), classrroomId from student group by classrroomId ;
查询字段这里的classroomId 必须在group by 后面的字段列表中存在,不然没有意义
例子:查询每个班有多少个学生
select count(*), classroomId from student gruop by classroomId;
例子:查询每个班姓陈的学生有多少个
select count(*),classroomId from student where stu_name like '陈%' group by classroomId
例子:查询哪个班的学生大于40
select count(*) ,classroomId from student group by classroomId having count(*)>40
例子:
总结:
8.按多个字段分组
9.排序放在最后
例子: