一.基本的查询语句格式
1.普通条件查询:select 字段1,字段2,… from 表名 where 条件;
2.去除重复的结果集:select distinct 字段1,字段2,… from 表名 where 条件;
3.查询字段1和字段2的和的结果集: select 字段1+字段2 from 表名 where 条件;
4.查询某个区间内的数据:select 字段1,字段2… from 表名 where 字段名 between 边界值1 and 边界值2;
5.查询某些散列值得数据:select 字段1,字段2… from 表名 where 字段名 in (值1,值2…);
6.模糊查询:select 字段1,字段2… from 表名 where 字段名 like 表达式;关于表达式我们常常需要用到占位符,—(下划线)表示任意单个字符,%表示任意多个字符。
为了方便理解,在这里我们创建一个student表,方便进行相关的举例说明。
-- 创建学生表
create table student(
son char(5),
sname varchar(10),
sex enum('男','女'),
MathScore int, -- 数学成绩
accessTime timeStamp -- 入学时间
);
-- 插入数据
insert into student(son,sname,sex,MathScore)
values('20201','张三','男',85),
('20202','李四','男',96),
('20203','王五','女',92);
-- 查询表中的所有数据
select son,sname,sex,MathScore,accessTime
from student;
-- 模糊查询
-- 查询姓张的同学的所有信息
select *
from student
where sname like '张%';
-- 查询姓名第二字为张的同学的所有信息
select *
from student
where sname like '_张%';
-- 查询名字包含张的同学的所有信息
select *
from student
where sname like '%张%';
二.排序查询
1.基本语法格式
select 字段1,字段2,… from 表名 where 条件 order by 字段1,字段2 … ASC/DESC;
2.举例:查询所有学生的数学成绩,并将其按降序排列
select sname,MathScore
from student
order by MathScore DESC;
3.注意事项:
(1)order by 子句中可以包含有多个字段,比较的规则为当第一个字段一样时,按第二个字段比较,以此类推。
(2)要在最后加上排序方式 ASC为升序,DESC为降序,默认为升序排列。
三.聚合函数
1.定义:将一列数作为一个整体进行纵向的计算
2.常见的聚合函数:count(计数),max(最大值),min(最小值),avg(平均值),sum(求和)
3.基本语法格式
select 聚集函数名(字段名) from 表名;
4.举例:查询所有学生数学成绩的平均分
select avg(MathScore) 平均分 -- 起别名
from student;
5.注意事项
count函数计数时,会排除null值。
四.分组查询
1.基本语法格式
select 字段1,字段2,… from 表名 group by 字段名;
2.举例:分别求男生和女生的数学成绩的平均分
select sex,AVG(MathScore)
from student
group by sex;
3.注意事项
(1)使用了group by 子句后后面只能跟聚合函数或则分组后的字段,使用其他的字段没有意义。
(2)我们可以使用where子句在分组之前进行限定,having子句在分组之后进行限定。还需要注意的是,where子句中不可以使用聚合函数,而having子句中可以使用聚合函数。
/*
1.对数学成绩大于90分以上才进行分组
*/
select sex,avg(MathScore)
from student
where MathScore > 90
group by sex;
/*
2.对数学成绩大于90分以上才进行分组,并且只显示大于平均分大于95的分组
*/
select sex,avg(MathScore)
from student
where MathScore > 90
group by sex
having avg(MathScore) > 95;
五.分页查询
1.基本语法格式
limit 开始的索引,每页的查询条数;
2.举例:每页显示2条记录,显示第一页
select son,sname,sex,MathScore,accessTime
from student
limit 0,2;
3.注意事项
(1)开始的索引为0
(2)通项公式:开始的索引 = (页码-1)*每页显示的条数
以上即使MySQL关于查询语句的基本知识,需要注意的是以上均为单表查询。