查询所有列
select * from students;
查询指定列
select id,name from students;
查询时指定别名
<!-- 在多表查询时经常使用表的别名 -->
select id as '编号',name as '姓名' from students as s;
查询时添加一个常量列
<!-- 需求:在查询students表时,添加一个班级列。内容为‘java班’ -->
select id,name,'java班' from students ;
查询时合并列
注意:合并列只能合并数值类型的字段
<!--需求:查询每个学生的servlet和jsp的总成绩 -->
select id,name,(servlet+jsp) as '总成绩' from students;
查询时去除重复记录
<!--语法【一】 需求:查询学生的性别 男 女-->
select distinct gender from students;
<!-- 语法【二】需求:查询学生的性别 男 女-->
select distinct(gender) from students;
条件查询(where)
【逻辑条件】and(与) or(或)
<!--查询id为2,且名字为李四的学生-->
select * from students where id=2 and name='李四';
<!--查询id为2,或者名字为张三的学生-->
select * from students where id=2 or name='张三';
【比较条件】>,<,>=,<=,=,<>(不等于),between and
<!-- 查询servlet成绩大于70分的 -->
select * from students where servlet > 70;
<!-- 查询jsp成绩大于等于75分且小于等于90分的 -->
select * from students where jsp>=75 and jsp<=90;
<!-- 查询jsp成绩大于等于75分且小于等于90分的【另外一个写法】 -->
select * from students where jsp between 75 and 90;
<!-- 查询性别不等于男的 -->
select * from students where gender<>'男';
【判空条件】 is null/is not null/ =”/<>”
null vs 空字符串
null:没有值
空字符串:有值得
<!-- 查询地址为空的学生 包括null和空字符串 -->
select * from students where address is null or address='';
<!-- 查询有地址的学生 -->
select * from students where address is not null and address<>'';
【模糊条件】like
通常使用以下标记
%:表示任意个字符
_:表示一个字符
<!--查询姓张的学生 -->
select * from students where name like '张%';
<!--查询姓李,并且名字只有两个字符的学生 -->
select * from students where name like '张_';
聚合查询
常用的聚合函数:求和函数sum(),平均函数avg(),max(),min(),count()
<!--需求:查询学生servlet的总成绩 -->
select sum(servlet) from students;
<!--需求:统计servlet平均分-->
select avg(servlet) from students;
<!--需求:查询servlet最高分-->
select max(servlet) from students;
<!--需求:查询servlet最低分 -->
select min(servlet) from students;
<!--需求:统计当前有多少学生 所有字段都统计一遍,然后取最大值-->
select count(*) from students;
<!-- count() 函数统计数量不包括null -->
select count(id) from students;
分页查询 (limit 其实行,查询几行记录)
其实行从0开始
<!--需求:只想查询出第1,2的记录 -->
select * from students limit 0,2;
排序查询(order by)
语法:order by 字段 asc/desc
asc:正序。数值:递增,字母:自然顺序(a-z)。
desc:反序。数值:递减,字母:自然反序(z-a)。
<!--需求:正序-->
select * from students order by id asc;
<!--默认正序-->
select * from students order by id;
<!--需求:反序-->
select * from students order by id desc;
<!--需求:按照servlet的正序,jsp的反序 -->
select * from students order by servlet asc,jsp desc;
分组查询 (group by)
<!--需求:查询男女的人数-->
select gender,count(*) from students group by gender;
分组筛选 (having)
/*查询总人数大于2的性别*/
select gender,count(*) from students group by gender having count(*)>2;