mysql第二讲
数据准备
student 学生表
enroll 报名表
格式 见 ppt 大家自行建表,和插数据
1.筛选条件
1.比较运算符
1.等于:=(注意,不是==)
select * from student where sex = 'male';
2.不等于:!= 或则 <>
select * from student where age != 18;
3.大于:>
4.小于:<
5.大于等于:>=
select * from student where age >= 18;
6.小于等于:<=
7.空:is null
select * from student where sex is null;
8.不为空:is not null
select * from student where sex is not nULL;
2.逻辑运算符
1. and 与
男性里面年龄大于18的数据
select * from student where sex='male' and age>18;
2. or 或
报名python_all 或者 python_web的学员
select * from enroll where course='python_all' or course='python_web';
3.其他操作
1.排序:order by 字段名
按照年龄排序
正序:select * from student order by age asc; # asc可以省略 默认
倒序:select * from student order by age desc;
2.限制:limit
只要三条:select * from student order by id limit 3;
从第二条开始:select * from student order by id limit 1, 3;
3.去重:distinct
查出表中所有的不同名字
select distinct student from enroll;
4.模糊查询:like
-任意多个字符:%
查询名字中包含'l':select * from enroll where student like '%l%';
查询名字中一'l'开头的:select * from enroll where student like 'l%';
-任意一个字符:_
查询名字是四个字符的:select * from enroll where student like '____';
**like如果不和 % 或 _ 就和= 一样的效果
5.范围查询
1.连续范围:between a and b 包含a和b
查询年龄介于17到20之间的学生:select * from student where age between 17 and 20;
*** 一般用数值,日期时间,字符串理论是可以的,但是一般不用
2.间隔范围:in
in (10, 20, ....)
查询 报名python_all 或者 python_web的学员
select * from enroll where course in ('python_web', 'python_all', 'abc');
2.聚合与分组(重点,难点)
统计:
1.统计个数:count(字段)
年龄大于18的有几个人:select count(id) from student where age>18;
***如果字段里有null 不会计算
2.求和:sum(字段)
报名python课程的支付总金额:select sum(pay) from enroll where course like '%python%';
3.平均值:avg(字段)
学生年龄平均值:select avg(age) from student;
4.最大值:max(字段)
学生年龄的最大值:select max(age) from student;
5.最小值:min(字段)
学生年龄的最小值:select min(age) from student;
分组:group py
按照课程分组查询 报名的总金额: select course, sum(pay) from enroll group by course;
按照学生分组查询报名的总金额:
*** 别名:select student, sum(pay) as total_pay from enroll group by student;
-having 子句 (因为:where关键字无法和统计函数用在一起)
按照学生分组,查询总金额大于5000的数据
select student, sum(pay) as total_pay from enroll group by student having sum(pay) > 5000;
-按照学生分组,查询总金额大于2000,报名python课程的数据
select student, sum(pay) as total_pay from enroll where course like '%python%' group by student having sum(pay) > 2000;
*** where 条件 要写到 group by 前面
-执行顺序。
一个查询语句同时包含了 别名,聚合函数,where 和 having 执行顺序:
1.最先执行 where
2.然后执行聚合函数和别名
3.最后再执行having
3.子查询(了解)
查询年龄小于平均年龄的学生数据
1.先查出平均年龄
select avg(age) from student;
2.在根据平均年龄查询
select * from student where age < 平均值;
子查询:select * from student where age < (select avg(age) from student);
要求:
1.嵌套在查询语句内
2.必须用括号包裹
4.连接查询(了解)(留到明天)
网友评论