学习目标2024.04.01
一.掌握where子句
二.掌握数据排序
三.掌握五种聚合函数的使用方法
四.了解分组和分页
ctrl+R 执行
一.where子句
1.字段的别名:
select card as 身份证/select card 身份证 -- as可以省略
3.消除重复记录:distinct
在查询时使用,过滤查询结果
4.where子句
where后面跟一个实现有选择的查询,在update和delete中也可以用。
select * from Student where id-1
5.select查询的基本规律
select 控制查询返回什么样的字段
where 控制查询返回了什么样的记录
6.比较运算符:
等于:= 不等于!=
大于:> 大于等于>=
小于:> 小于等于<=
7.逻辑运算符:
and:有两个条件,条件1and条件2,两个条件必须同时满足
or:有两个条件,条件1or条件2,两个条件满意一个即可
not:只有一个条件,not条件。
如果条件为满足,not后为不满足;如果条件不满足,not后为满足。
8.模糊查询:
like实现模糊查询
%代表任意多个字符
_代表任意一个字符
字段名 like ‘字符%’
9.空判断:
null 代表什么也没有 判断为空为:is null
‘ ’代表长度为0 判断不为空:is not null
![image-
二.排序
1.排序:order by
asc默认从小到大排序
desc从大到小排序
-
当一条select语句出现了where和order by
select * from 表名 where条件 order by 字段1,字段2
三.聚合函数
不能用在where中的函数中
1.count( 字段名):求select返回的记录总数。
括号中写*与字段名结果是相同的。
2.max(字段名):查询指定字段里的最大字段值。
3.min(字段名):查询字段的最小值。
4.sum(字段名):查询字段的总和。
5.avg(字段名):查询学生的平均年龄,忽略null值。不参与为分母。
select count * from students where class='一班';
四.数据分组
-
group by 字段名
-
select 聚合函数 from 表名 where 条件 group by 字段
-
group by 就是配合聚合函数使用的
select age,count(*) from student group by age
-
where与group by 和 order by的顺序
select * from 表名 where 条件 group by 字段 order by 字段
-
分组后的数据筛选
having子句总是出现在group by 之后
having 字段1,...聚合...
select * from 表名 group by 字段 having 条件
用where查询男生总数 where 先筛选符合条件的记录,然后再聚合统计 select count(*) from students where sex ='男'
用having查询男生总数 having先分组聚拢统计,在统计的结果中筛选 select count(*) from students group by sex having sex ='男'
-
having 配合聚合函数的使用
求班级人数大于3人的班级名字 select class from students group by class having count(*)>3
where后面不能使用聚合函数,但having可以使用聚合函数
-
-
where是对表的原始数据进行筛选
-
having是对group by之后已经分组的数据进行筛选
-
having可以使用聚合函数,where不能用聚合函数
查询班级总人数大于2人的班级名称以及班级对应的总人数 select class,count(*) from students group by class having count(*)>2;
查询平均年龄大于30岁的班级名称和班级总人数 select class,count(*) from students group by class having avg(age)>30;
五.数据分页显示
-
获取分行
-
select * from 表名 where 条件group by 字段order by 字段 limit start ,count
-
limit 开始行,获取行数,start 可以省略,默认从第一行开始
-
limit总是出现在查询语句的最后
select * from 表名 limit start,count
-
从start开始,获取count条数据
查询前三行记录 select * from students limit 0,3 select * from students limit 3
查询年龄最小的女同学信息 <!-- 有最什么的可以用order by结合 limit 排序完显示第一行 --> select * from students where sex='女' order by age limit 1;
2.分页
-
已知:每页显示m条记录,求:查询n页的数据
select * from students limit (n-1)*m,m
-
求总页数
已知每页页数,求一张表需要几页显示完
-
求总页数
-
总页数/每页的记录数
-
如果结果是整数,那么就是总页数,如果结果有小数,那么就在结果的整数上加一
-