聚合
为了快速得到统计数据,提供了5个聚合函数
count(*)表示计算总行数,括号中写星与列名,结果是相同的
查询学生总数
select count(*) from students;
max(列)表示求此列的最大值
查询女生的编号最大值
select max(id) from students where gender=0;
min(列)表示求此列的最小值
查询未删除的学生最小编号
select min(id) from students where isdelete=0;
sum(列)表示求此列的和
查询男生的编号之后
select sum(id) from students where gender=1;
avg(列)表示求此列的平均值
查询未删除女生的编号平均值
select avg(id) from students where isdelete=0 and gender=0;
排序
为了方便查看数据,可以对数据进行排序
select * from 表名
order by 列1 asc|desc,列2 asc|desc,...
将行数据按照列1进行排序,如果某些行列1的值相同时,则按照列2排序,以此类推
默认按照列值从小到大排列
asc从小到大排列,即升序
desc从大到小排序,即降序
查询未删除男生学生信息,按学号降序
select * from students
where gender=1 and isdelete=0
order by id desc;
查询未删除科目信息,按名称升序
select * from subject
where isdelete=0
order by stitle;
完整的select语句
select distinct *
from 表名
where ....
group by ... having ...
order by ...
limit star,count
执行顺序为:
from 表名
where ....
group by ...
select distinct *
having ...
order by ...
limit star,count
实际使用中,只是语句中某些部分的组合,而不是全部
分页
获取部分行
当数据量过大时,在一页中查看数据是一件非常麻烦的事情
select * from 表名
limit start,count
从start开始,获取count条数据
start索引从0开始
已知:每页显示m条数据,当前显示第n页
求总页数:此段逻辑后面会在python中实现
查询总条数p1
使用p1除以m得到p2
如果整除则p2为总数页
如果不整除则p2+1为总页数
求第n页的数据
select * from students
where isdelete=0
limit (n-1)*m,m
本文详细介绍了SQL中的五个聚合函数:count(*)、max(列)、min(列)、sum(列)、avg(列),并展示了如何使用这些函数进行数据统计。此外,还讲解了如何使用orderby进行数据排序,包括升序asc和降序desc,以及如何结合where子句进行条件筛选。
851

被折叠的 条评论
为什么被折叠?



