Mysql50句练习下
前言: 故不积跬步,无以至千里
安装地址
https://www.runoob.com/mysql/mysql-install.html
scrpit:
1 | #!/bin/sh |
sql 答案参考这里
1 | 25、查询各科成绩前三名的记录 |
– 26、查询每门课程被选修的学生数
1 | SELECT |
– 27、查询出只有两门课程的全部学生的学号和姓名
1 | SELECT |
– 28、查询男生、女生人数
1 | SELECT |
select st.s_sex,count(1) from Student st group by st.s_sex
这样的写法会更好,对student进行分类,再进行求count聚合
– 29、查询名字中含有”风”字的学生信息
1 | SELECT |
– 30、查询同名同性学生名单,并统计同名人数
1 | SELECT |
select st.*,count(1) from Student st group by st.s_name,st.s_sex having count(1)>1
答案处用的还是分组的思想,我用的是比较的方法,结果相同,需要分析性能
– 31、查询1990年出生的学生名单
1 | SELECT |
32、查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列
1 | SELECT |
– 33、查询平均成绩大于等于85的所有学生的学号、姓名和平均成绩
1 | SELECT |
– 34、查询课程名称为”数学”,且分数低于60的学生姓名和分数
1 | SELECT |
– 35、查询所有学生的课程及分数情况;
1 | SELECT |
– 36、查询任何一门课程成绩在70分以上的姓名、课程名称和分数;
1 | SELECT |
– 37、查询不及格的课程(存疑)
1 | SELECT |
– 39、求每门课程的学生人数
1 | SELECT |
– 40、查询选修”张三”老师所授课程的学生中,成绩最高的学生信息及其成绩
1 | SELECT |
– 41、查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩
1 | SELECT |
– 42、查询每门功成绩最好的前两名
1 | SELECT |
SELECT
a.*
FROM
( SELECT c_id, COUNT( s_id ) AS count FROM Score GROUP BY c_id HAVING count >= 5 ORDER BY c_id DESC ) AS a,
( SELECT c_id, COUNT( s_id ) AS count FROM Score GROUP BY c_id HAVING count >= 5 ORDER BY count DESC ) AS b
WHERE
a.c_id = b.c_id
1 | -- 44、检索至少选修两门课程的学生学号 |
SELECT
s_id
FROM
Score
GROUP BY
s_id
HAVING
COUNT( s_score ) >= 2
1 | -- 45、查询选修了全部课程的学生信息 |
SELECT
st.*
FROM
Student st,
Score sc
WHERE
st.s_id = sc.s_id
GROUP BY
sc.s_id
HAVING
COUNT( s_score ) >= 3
1 |
|
SET @dt = DATE_FORMAT( NOW(), ‘%Y-%m-%d’ ); –设置当前时间为dt
SELECT
s_name,
TIMESTAMPDIFF(
YEAR,
s_birth,
DATE_FORMAT( NOW(), ‘%Y-%m-%d’ ))
FROM
Student;
1 | -- 47、查询本周过生日的学生 |
– 获取一周的日子
SET @bd = DAYOFWEEK( @dt );
SET @startmonth = MONTH (
DATE_ADD( @dt, INTERVAL - @bd + 1 DAY ));
SET @startday = DAY (
DATE_ADD( @dt, INTERVAL - @bd + 1 DAY ));
SET @endmonth = MONTH (
DATE_ADD( @dt, INTERVAL 7 - @bd DAY ));
SET @endday = DAY (
DATE_ADD( @dt, INTERVAL 7 - @bd DAY ));
SELECT
Student.*
FROM
Student
WHERE
MONTH ( s_birth ) >= @startmonth
AND MONTH ( s_birth ) <= @endmonth AND DAY ( s_birth ) >= @startday
AND DAY ( s_birth ) <= @endday
1 | -- 48、查询下周过生日的学生 |
SET @bd = DAYOFWEEK( @dt );
SET @startmonth = MONTH (
DATE_ADD( @dt, INTERVAL 7 - @bd + 1 DAY ));
SET @startday = DAY (
DATE_ADD( @dt, INTERVAL 7 - @bd + 1 DAY ));
SET @endmonth = MONTH (
DATE_ADD( @dt, INTERVAL 15 - @bd DAY ));
SET @endday = DAY (
DATE_ADD( @dt, INTERVAL 15 - @bd DAY ));
SELECT
Student.*
FROM
Student
WHERE
MONTH ( s_birth ) >= @startmonth
AND MONTH ( s_birth ) <= @endmonth AND DAY ( s_birth ) >= @startday
AND DAY ( s_birth ) <= @endday
1 | -- 49、查询本月过生日的学生 |
SELECT
st.*
FROM
Student st
WHERE
MONTH ( @dt ) = MONTH ( st.s_birth )
1 | -- 50、查询下月过生日的学生 |
SELECT
st.*
FROM
Student st
WHERE
MONTH (
DATE_FORMAT( NOW(), ‘%Y-%m-%d’ )) + 1 = MONTH ( st.s_birth );
````