一:创建表,导入数据
具体的关于建表的代码,想要的朋友们可以在评论里面问我哈
分别有4张表:
course表,sc表,student表,teacher表
course表:
sc表
student表:
teacher表:
二:开始刷题啦,加油
1、查询“01”课程比“02”课程成绩高的所有学生的学号;
SELECT
t1.sid
FROM
( SELECT sid, cid, score AS score1 FROM sc WHERE cid = 01 ) t1
LEFT JOIN
( SELECT sid, cid, score AS score2 FROM sc WHERE cid = 02 ) t2
ON t1.sid = t2.sid
WHERE
t1.score1 > t2.score2
2、查询平均成绩大于60分的同学的学号和平均成绩;
SELECT
sid,
avg( score ) av_score
FROM
sc
GROUP BY
sid
HAVING
av_score > 60
3、查询所有同学的学号、姓名、选课数、总成绩
SELECT
student.sid,
student.sname,
t1.c_cid,
t1.sum_score
FROM
student
LEFT JOIN ( SELECT sid, count( cid ) c_cid, sum( score ) sum_score FROM sc GROUP BY sid ) t1
ON student.sid = t1.sid
4、查询姓“李”的老师的个数;
SELECT
count(*) AS nums
FROM
( SELECT tname FROM teacher WHERE tname LIKE '李%' ) t1
5、查询没学过“张三”老师课的同学的学号、姓名;
(可以先找出学了张三老师的学号,然后在student表中过滤这些就好了)
SELECT
sid,
sname
FROM
student
WHERE
sid NOT IN (
SELECT
sc.sid
FROM
teacher
LEFT JOIN course ON teacher.tid = course.tid
LEFT JOIN sc ON course.cid = sc.cid
WHERE
teacher.tname = '张三'
)
6、查询学过编号“01”并且也学过编号“02”课程的同学的学号、姓名;
SELECT
student.sid,
student.sname
FROM
student
WHERE
student.sid IN (
SELECT
t1.sid
FROM
( SELECT sid, cid FROM sc WHERE sc.cid = 01 ) t1
INNER JOIN ( SELECT sid, cid FROM sc WHERE sc.cid = 02 ) t2 ON t1.sid = t2.sid)
7、查询学过“张三”老师所教的课的同学的学号、姓名;
SELECT
student.sid,
student.sname
FROM
student
WHERE
sid IN (
SELECT
sc.sid
FROM
sc
WHERE
sc.cid IN (
SELECT
cid
FROM
course
WHERE
tid = ( SELECT teacher.tid FROM teacher WHERE teacher.tname = "张三" )))
8、查询课程编号“01”的成绩比课程编号“02”课程低的所有同学的学号、姓名;
SELECT
student.sid,
student.sname
FROM
student
WHERE
student.sid IN (
SELECT
t1.sid
FROM
( SELECT * FROM sc sc1 WHERE cid = 01 ) t1
INNER JOIN ( SELECT * FROM sc sc2 WHERE cid = 02 ) t2 ON t1.sid = t2.sid
WHERE
t1.score < t2.score)
9、查询所有课程成绩小于60分的同学的学号、姓名;
SELECT
student.sid,