手机扫码查看
2020javaweb教程之mysql习题集合
回顾知识
简单查询:select*from 表名;
查询指定列:select sname,score from 表名;
条件查询:
比较运算符:
查询性别为女,并且年龄小于50的记录:
select*from 表名 where sex=’女’ and age<50;
查询学号为S_1001,或者姓名为liSi的记录
select*from 表名 wher sid=’S_1001′ or sname=’lisi’;
查询学号为S _ 1001 ,S _ 1002,S _ 1003的记录 IN(set)
select*from 表名 where sid=’S_1001′ or sid=’S_1002′ or sid=’S_1003′;
或者:
select*from 表名 where sid in(‘S_1001′,’S_1002′,’S_1003’);
查询学号不是S_1001,S_1002,S_1003的记录
select*from 表名 where sid not in(‘S_1001′,’S_1002′,’S_1003’);
查询年龄为null的记录
select*from 表名 where age is null;
查询年龄在20到40之间的学生记录
select*from 表名 wher age between 20 and 40;
查询性别非男的学生记录
select*from 表名 where sex!=’男’;
select*from 表名 where not sex=’男’;
排序:desc降序,asc升序
字段控制查询:
去重:distinct
select distinct sname from 表名;
查看雇员的月薪与佣金之和
select *,concat(sname,’#’,score) from 表名;
将null值转换为0运算
select *,salary+ifnull(comm,0) from 表名;
给列名添加别名(可省略 as 关键字)
select sname,km,ifnull(score,0) test from score;
查询所有雇员,按月薪降序排序,如果月薪相同时,按编号升序排序
select*from emp order by sal desc,empno asc;
分组查询
查询工资总和大于9000的部门编号以及工资和
select depno,sum(sal) from emp group by depno having sum(sal)>9000
having与where区别
1.having是在分组后对数据进行过滤,where是在分组前对数据进行过滤。
2.having后面可以使用聚合函数,where后面不可以使用聚合
3.where是对分组前记录的条件,如果某行记录没有满足where子句的条件,那么这行记录不会参加分组;
而having是对分组后数据和约束
总结查询
查询语句书写顺序:
select 列 from 表名 where–>group by 分组名–>having–>order by排序–>limit 限制
查询语句执行顺序:
from 表名 where–>group by–>having–select–>order by–>limit
课后习题:
查询两门及两门以上不及格的学生姓名
select sname from stu group by sname having sum(score<60)>=2
查询学生平均分
select avg(score)from stu group by sname
查询姓名是张三的学生成绩
select sname,km,score from 表名 where sname=’张三’;
将学生信息按照分数倒序
select*from 表名 order by score desc
获取学生信息中 分数最低的学生姓名和分数最高的学生姓名
select sname,score from 表名 where score=(select max(score) from 表名)
or
score=(select min(score) from 表名)
查询两门及两门以上不及格同学的平均分。
select sname,sum(score<60) gk,avg(score) pj from 表名 group by sname having gk>=2;



发表回复