2020年8月4日20:22:06
1、Select 查询表中的数据
-- select 列限定 from 表限定 where 行限定
select * from teacher where id= 1; --查询teacher表中id为1 所有信息
select * from teacher; --查询teacher表中的所有信息
select name from teacher where id= 1; --查询teacher表中 id为1 的name值
-- 示例代码
create table teacher(
id int,
`name` varchar(100)
);
insert into teacher (id, `name`) values (1,'张老师');
insert into teacher (id, `name`) values (2,'王老师');
select * from teacher; -- 查询teacher表中所有的数据
select name from teacher; -- 查询所有行的name
select name from teacher where id = 1; -- 查询 id 为 1 的讲师姓名
2、like 模糊查询
-- % 匹配任意字符
-- _ 匹配单个字符
-- select 列限定 from 表限定 where 列名 like '值' ;
select * from student where name like '张%'; -- 把name中,把姓张的查询出来
select * from student where name like '__'; -- 把 name中,姓名有两个字的查询出来
3、Order by 排序
-- select 列限定 from 表限定 order by 列名 asc/desc;
-- Asc : 升序
-- Desc : 降序
select * from student order by score desc; -- 查询所有学生信息,以成绩降序
select * from student order by score desc , id asc; -- 查询所有学生信息,按成绩降序,
--如果成绩相同,按照id升序
4、 Limit
-- select 列限定 from 表限定 limit 条数;
-- select 列限定 from 表限定 limit 开始值(不包含) ,条数;
select * from student order by score desc limit 3; -- 查询学生表,分数前三名的信息
select * from student order by score desc limit 1,2; -- 查询学生表,分数第二名和第三名
5、group by 单表查询
-- select count(*),max(字段名),min(字段名)... from 表名 group by 字段名;
select count(*) from student; -- 查看学生表共有多少学生
select count(*) from student where score > 90; -- 查看学生表中分数大于90分的有多少学生
select teacher_id, count(*) as stu_count from student group by teacher_id; -- 查询每个老师分别带了多少学生(显示老师id即可)
select teacher_id, count(*) as stu_count,max(score) as stu_max_score from student group by teacher_id; -- 查询每个老师带的学生中的最高分数
select teacher_id, sum(score) as sum,avg(score) as avg from student group by teacher_id; -- 查询每个老师所带学生的总成绩与平均分
6、having 对分组的结果进行过滤
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60; -- 每个讲师所带学生的平均分大于60的