1.查询所有列
查询的关键字 select
select * from student;
2.查询指定列
select id,name from student;
3.查询时指定别名 注意:在多表查询时经常使用别名
select id as‘编号’,name as ‘姓名’ from student;
4.查询时添加常量列
需求:在查询student表时,添加一个班级列,内容为‘java就业班’
select id,name,age ,‘java就业班’as ‘年级’from student
5.查询时 合并列
给student表添加servlet和jsp成绩列
alter table student add servlet int,add jsp int;
update student set servlet=70,jsp=85 where id=1;
select id,name,(servlet+jsp) as ‘总成绩’ from student;
注意:合并列只能合并数值类型的字段
6.查询时取出重复记录 distinct
需求: 查询学生的性别 男女
select gender from student;
select distinct gender from student;
另一种语法: select distinct(gender) from student;
7.条件查询 where
1.逻辑条件 and or
需求: 查询id为2,且姓名为李四的学生
select * from student where id=2 and name=‘李四’; 并集
需求:查询id为2,或姓名为张三的学生
select * from student where id=2 or name=‘张三’; 交集
2.比较条件 > < >= <= == <> between and
需求: 查询servlet 成绩大于70分的学生
select * from student score>70;
需求: 查询jsp成绩大于等于75,且小于等于90分的学生
select * from student jsp>=75 and jsp<=90;
另外一种语法: select * from student where jsp between 75 and 90; 包前包后
select * from student where gender <> ‘男’;
3.判空条件 null 空字符串 is null 、is not null ==‘’<>”
需求:查询地址为空的学生 包括null和空字符串
有两种 一种是有值得、‘’ 空字符串
另一种是没有值得
select * from student where address == null;
select * from student address is null or address=‘’;
需求:查询有地址的学生
select * from student where address is not null or address <> ” ;
4.模糊条件 : like
需求: 查询姓 ‘张’ 的学生
select * from student where name like‘张%’;
% :表示任意字符
需求: 查询姓 李的,且姓名只有两个字的学生
select * from student where name lile ‘李_’
查询表中所有学生的信息
select * from student;
查询表中所有的学生的姓名和对应的英语成绩
select name english from student;
过滤表中英语成绩的重复数据
select distinct(english) from student;
查询姓名为李一的成绩
select * from studnet where name=‘李一’;
查询总分大于200分的所有同学
select * from student where (chinses+math+english)>200;
在所有学生总分数上面加10分
select id,name,(chinese+english+math+10) as ‘总成绩’ from student;
聚合查询 使用聚合函数的查询
常用的聚合函数: sum() avg() max() min() count()
需求:查询学生的servlet的总成绩 sum:求和函数
select sum(servlet )as ‘servlet的总成绩’from student;
需求:查询学生的servlet的平均分
select avg(servlet) as “servlet的平均分” from student;
需求:查询当前servlet最高分
select max(servlet) as ‘最高分’ from student;
最低分
select min(servlet) as“最低分” from studnet;
需求:统计当前有多少学生(count())
select count(*) from student; 所有
select count(id) from student; 所有id
注意 count()函数统计的数量不包含null的数据
使用count()统计表的记录数,要使用不包含null的字段
分页查询 limit 起始行 ,查询几行
select * from student limit 0,2;
查询排序 order by desc/asc
需求 按照id 排序
select * from student order by id desc;
注意: 多个排序条件
select * from student order by servlet asc,jsp desc;
分组查询 group by
需求:查询男女的人数
预期结果
男 3
女 2
把学生按照性别分组 group by gender
统计每组的人数
select gender ,count(*)from student group by gender;
分组查询后筛选 使用group by、 之后不能跟where、 要是用having
需求: 查询人数大于2的性别
1.查询每个性别的人数
2.筛选出人数大于2的记录
分组之前使用where关键字 分组之后使用having关键字
select gender ,count() from student (where)group by gender having count()>2;