AI智能
改变未来

MySQL之单表查询


单表查询(组函数)

常用组函数有 :
count() : 总条数
max(字段名) : 最大值
min(字段名) : 最小值
avg(字段名) : 平均值
sum(字段名) : 总和
示例数据
create table student (
id int ,
name varchar(20),
teacher_id int,
score decimal(18,2) ,
primary key (id)
);
create table teacher(
id int ,
name varchar(20),
primary key (id)
);
insert into teacher (id,name)values(1,‘张老师’);
insert into teacher (id,name)values(2,‘王老师’);
insert into student (id,name,teacher_id,score)values(1,‘张三’,1,90);
insert into student (id,name,teacher_id,score)values(2,‘李四’,2,88.9);
insert into student (id,name,teacher_id,score)values(3,‘王五’,1,45.7);
insert into student (id,name,teacher_id,score)values(4,‘赵六’,1,84);
insert into student (id,name,teacher_id,score)values(5,‘小明’,2,92.5);
insert into student (id,name,teacher_id,score)values(6,‘小红’,2,47);
语法 :
select count(),max(字段名),min(字段名)… from 表名 group by 字段名;
如 : 查看学生表共有多少学生
select count() from student;
如 : 查看学生表中分数大于90分的有多少学生
select count() from student where score > 90;
Group by
如 : 查询每个老师分别带了多少学生(显示老师id即可)
select teacher_id, count() as stu_count from student group by teacher_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;
Having
刚才我们使用group by 和 组函数,可以对数据进行分组查询,并且也可以查询到平均值等数据
但是有时候我们也需要做一些判断,比如求出平均值了,我只想要平均值 大于60分的平均分数,这时候用where就不行了
select teacher_id, avg(score) as avg from student where avg > 60 group by teacher_id;
这个时候就需要使用having进行过滤
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60;

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » MySQL之单表查询