先创建一个表
1.全列查找
select * from [表名];
2.指定列查找
select [列名] from [表名];
3.查找并加和
算出总成绩: select name,chinese+english+math from exam_result;
给某一个成绩加分: select name,chinese+5 from exam_result;
4.查询字段指定列名
select name,chinese+english+math as total from exam_result;
(其中as可以省略)
5.去重
select distinct math from exam_result;
(不会改变原来的表结构)
6.排序
a)查找数学成绩升序排序
select * from exam_result order by math;
b)查找数学成绩降序排序
select * from exam_result order by math desc;
c)查找总成绩降序排序
select name,chinese+math+english as total from exam_result order by total desc;
d)按照(指定)多个列排序
select * from exam_result order by chinese desc,math desc,english desc;
7.条件查找 a)查找语文成绩为空的记录
select * from exam_result where chinese is null; select * from exam_result where chinese <=> null;
此表格中没有为null的值,所以查找出来为0;
b)查找语文成绩不及格的信息
select * from exam_result where chinese < 60;
c)查找语文成绩大于英语成绩的信息
select * from exam_result where chinese > english;
d)查找总成绩大于200的信息
select name,chinese+math+english as total from exam_result where chinese+math+english < 200; (where里面不能用别名)
e)同时满足两科大于70的
select * from exam_result where chinese>70 and math>70;
f)查询语文在【20,40】之间的
select * from exam_result where chinese between 20 and 40; (也可以用and)
g)查询数学是97或者90的
select * from exam_result where math in (90.0,97.0); (也可以用or)
h)模糊查询 like (查询效率低)
%:匹配任意个任意字符 _ :匹配一个任意字符
i)查找姓孙同学的成绩
select * from exam_result where name like ‘孙%’; select * from exam_result where name like ‘孙__’;(两个下划线)
ii)查找姓所有同学的数学成绩是9开头的
select * from exam_result where math like ‘9%’;
8.分页查找
a)查找总分的前三名
select name,chinese+math+english as total from exam_result order by total desc limit 3;
b)查找总分的前4 5 6名
select name,chinese+math+english as total from exam_result order by total desc limit 3 offset 3;
( offset 3 可以当成下标)
如果limit写的超出了数据范围,那么不会报错,返回从开始位置到最后位置的全部值;
如果offset写的超出了范围,不会报错,返回一个空的结果;