mysql -uroot < hellodb.sql,use hellodb数据库
(1) 在students表中,查询年龄大于25岁,且为男性的同窗的名字和年龄ide
select Name,Age from students where Age>25;性能
select ClassID,avg(Age) from students group by ClassIDui
(3)显示第2题中平均年龄大于30的分组及平均年龄3d
select ClassID,avg(Age) from students group by ClassID having avg(Age) > 30blog
select * from students where name like 'L%';
select * from students where TeacherID is not null;
select * from students order by age desc limit 10;
select * from students where age between 20 and 25;
二、导入hellodb.sql,如下操做在students表上执行
select classID,count(*) as total_num from students group by ClassID;
select gender,sum(Age) from students group by gender;
select ClassID,avg(Age) from students group by ClassID having avg(Age) > 25;
(4)以Gender分组,显示各组中年龄大于25的学员的年龄之和
select gender,sum(Age) from students where age > 25 group by gender;
select s.stuid as stu_id,s.name as stu_name,sc.score,c.course from students as s inner join scores sc on s.stuid=sc.stuid inner join courses c on sc.courseid=c.courseid where s.stuid <= 5;
select s.stuid as stu_id,s.name as stu_name,sc.score,c.course from students as s inner join scores sc on s.stuid=sc.stuid inner join courses c on sc.courseid=c.courseid where sc.score > 80;
(7)求前8位同窗每位同窗本身两门课的平均成绩,并按降序排列
select s.stuid,s.name,avg(sc.score) as avg_score from students as s inner join scores sc on s.stuid=sc.stuid group by stuid order by avg_score;
(8)取每位同窗各门课的平均成绩,显示成绩前三名的同窗的姓名和平均成绩
select s.name,avg(sc.score) from students as s inner join scores sc on s.stuid=sc.stuid group by s.name order by avg(sc.score) desc limit 3;
第一步:通过筛选,决定使用courses表、coc表和students表作查询
第二步:经过联系将三个表联系在了一块儿,select count(s.stuid),c.course from students as s inner join coc on s.classid=coc.classid inner join courses c on coc.courseid=c.courseid;
第三步,分组,获得的这个表用哪一个分组合适?毫无疑问,用course字段合适,将该字段加入分组,select count(s.stuid) as Stu_Num,c.course from students as s inner join coc on s.classid=coc.classid inner join courses c on coc.courseid=c.courseid group by c.course;
有子查询和内链接两种写法,虽然子查询方式便于理解,但因为数据库性能不高在此推荐用内链接的写法
第一种,子查询:select name,age from students where age > (select avg(Age) from students);
第二种,内链接写法:slect s.name,age from students as s inner join (select avg(age) as age from students) as ss on s.age > ss.age;
(11)显示其学习的课程为第一、2,4或第7门课的同窗的名字
select s.name,a.courseid from students as s inner join (select * from coc where courseid in ('1','2','4','7')) as a on s.classid=a.classid;
(12)显示其成员数最少为3个的班级的同窗中年龄大于同班同窗平均年龄的同窗
先查询成员数量最少为3个的班级,且每一个班的平均年龄,select classid,count(stuid),avg(age) from students group by classid having count(stuid)>=3;
再将学生表的name、age与生成的该表作对比,对比时候用where条件判断每一个学生分别对应本身的classid进行比较
(13)统计各班级中年龄大于全校同窗平均年龄的同窗
select stuid,name,age,classid from students where age > (select avg(age) from students);