MySQL的系统函数
子任务 1 用于文本串的处理函数
例 1 使用 LEFT()函数返回 id 为 1 的记录内容的左侧 4 个字符
select id,left(text,4) as left_content
from
f_table
where
id=1;
例 2 使用 SUBSTRING(string,m,n)函数截取表中第二条记录从第 7 个字符开始的 5 个字符。
select id,substring(text,7,5) as sum_7_5
from f_table
where id=2;
函数中 m 的值可以省略,默认为截取到字符串最后。
例 3 使用 LENGTH()函数求取第三条记录中 text 内容的长度
select id,length(text) from f_table where id=3;
例 4 使用 LOCATE()函数计算第 2 条记录中字母 o 第一次出现的位置
select id,locate('o',text) from f_table where id=2;
例 5 使用 LOWER ()函数将第 3 条记录的所有内容转换为小写
select id,lower(text) from f_table where id=3;
例 6 使用 TRIM ()函数去掉第 4 条记录内容两侧的空格。
select id,trim(text) from f_table where id=4;
LTRIM()和 RTRIM()函数的使用方法类似。
例 7 使用 SOUNDEX ()函数查询记录中发音与‘李’类似的记录。
select * from f_table where soundex(text)=soundex('li');
子任务 2 时间和日期函数
任务 2 根据业务需求查询表中的汇总信息
子任务 1 对指定字段的数据汇总求和
sum()函数。
例 8: 计算 Score 表中 150101 同学各门课程的期末成绩总分。
select StuID,sum(ExamScore)
from Score
where StuID=’150101’;
子任务 2 对指定字段的数据求平均值
avg()函数
例 9: 计算 Score 表中 150101 同学各门课程的期末成绩平均分。
select StuID,avg(ExamScore)
from Score
where StuID='150101';
子任务 3 对指定字段的数据求最大值
max()函数
例 10:综合运用函数,求 Student 表中学生的最大年龄。
select max(year(now())-year(StuBirthday) ) as 最大年龄
from Student;
子任务 4 对指定字段的数据求最小值
min() 函数
例11:计算 Score 表中 150101 同学各门课程的期末成绩最低分。
select StuID,min(ExamScore)
from Score
where StuID='150101';
子任务 5 统计表中记录的总行数
count() 函数
- count(*): 统计记录的总条数,包含空值 。
- count(字段名) :统计某个字段有值的记录个数,不包含该字段为空值(null)的记录。
- count(distinct 字段名) : 去掉重复值之后,再统计该字段有值的记录个数。
select count(*) from student;
select count(1) from student;
select count(StuID) from student;
例12:统计 Student 表中有多少条记录
例 13:统计 Course 表里备注不为空的有多少条记录
例 14:统计 Student 表中有多少个班级
select count(distinct ClassID) from Student;
任务 3 根据业务需求查询表中的分类信息
子任务 1 实现对信息的分组查询
使用group by 子句
语法为:
group by 字段 1,字段 2,…字段 n
例15:统计 Student 表中男生和女生的人数
select StuSex, count(*) as 人数
from Student
group by StuSex;
例 16:统计 Student 表中每个地区的男生和女生数
总结:分组后可以看哪些字段:一般是分组的字段,和使用聚合函数的列; group by 后跟多个字段时,即如想按多个字段分组,则需多个字段都相同才能分为一组。
rollup 子句
select StuName, Native, count(*) as 人数
from Student
group by Native with rollup;
可以包含汇总行。
例 17:统计 Student 表中每个地区的男生和女生数,并汇总每个地区的总人数。
select Native, StuSex, count(*) as 人数
from Student
group by Native, StuSex
with rollup;
select Native, StuSex, count(*) as 人数
from Student
group by Native, StuSex
with rollup;
Having 子句
group by
字段
having
筛选条件