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);