排序
select * from 表名
order by 列1 asc|desc,列2 asc|desc,…
在这里插入代码片
例1:查询所有学生信息,按年龄从小到大排序
select * from students order by age
例2:查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大排序
select * from students order by age desc,studentNo
例3:中文名字排序按字母
select * from students order by convert(name using gbk) desc;
聚合函数
例1:查询学生总数
select count(*) from students;
例2:查询女生的最大年龄
select max(age) from students where sex='女';
例3:查询1班的最小年龄
select min(age) from students;
例4:查询北京学生的年龄总和
select sum(age) from students where hometown='北京';
例5:查询女生平均年龄
select sum(age) from students where hometown='北京';
练习
查询所有学生的最大年龄,最小年龄,平均年龄
select sum(age) from students where hometown='北京';
分组
select 列1,列2,聚合... from 表名 group by 列1,列2...
例1:查询各种性别的人数
select sex,count(*) from students group by sex
例2:查询各种年龄的人数
select age,count(*) from students group by age
练习:
查询每一个班级,最大,最小,平均年龄
select class, min(age) 最小年龄, max(age) 最大年龄, avg(age) 平均年龄 from students group by class
查询每一个班级,男生和女生的数量
分组后数据筛选
having 必须用在group by 之后。
方案一: 条件查询实现
select count(*) from students where sex='男'
方案二:分组,之后过略实现
select sex,count(*) from students group by sex having sex='男'
练习:
查询1班除外其他班级学生的最大,最小,平均年龄
- 分组筛选
select class, max(age), avg(age), min(age) from students group by class having class!='1班';
- 条件分组
select class, max(age), avg(age), min(age) from students where class!='1班' group by class
总结 where 和 having
分页、获取部分行
例1:查询前3行学生信息
select * from students limit 0,3
(n-1)*m, m
n:为第几页
m:每一页显示有几条
select * FROM students limit 0,3; #0=3(1-1)
select * FROM students limit 3,3; #3=3(2-1)
select * FROM students limit 6,3; #6=3(3-1)