-- 1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数
SELECT a.*,b.s_score as '01-课程',c.s_score as '02-课程'
FROM student a
JOIN score b on a.s_id = b.s_id AND b.c_id = '01'
LEFT JOIN score c on a.s_id = c.s_id AND c.c_id='02' OR c.c_id=NULL
WHERE b.s_score > c.s_score
-- 2、查询"01"课程比"02"课程成绩低的学生的信息及课程分数
SELECT a.*,b.s_score as '01',c.s_score AS '02'
FROM student a
JOIN score b on a.s_id = b.s_id AND b.c_id = '01'
left JOIN score c on a.s_id = c.s_id AND c.c_id = '02'
where b.s_score<c.s_score
-- 3、查询平均成绩大于等于60分的同学的学生编号和学生姓名和平均成绩
SELECT a.s_id AS '学号',a.s_name AS '名字',ROUND(AVG(b.s_score),2) AS '大于60平均成绩'
FROM student a
JOIN score b on a.s_id = b.s_id
GROUP BY a.s_name,a.s_id
HAVING ROUND(AVG(b.s_score),2) >= 60
ORDER BY a.s_id desc
-- 4、查询平均成绩小于60分的同学的学生编号和学生姓名和平均成绩-- (包括有成绩的和无成绩的)
SELECT a.s_id AS '学号',a.s_name AS '名字',ROUND(AVG(b.s_score),2) AS '小于等于60平均成绩'
FROM student a
JOIN score b on a.s_id = b.s_id
GROUP BY a.s_name,a.s_id
HAVING ROUND(AVG(b.s_score),2) <= 60 UNION
SELECT b.s_id AS '学号',b.s_name AS '名字',0 AS '小于等于60平均成绩'
FROM student b
WHERE b.s_id not in ( -- 获取没有成绩的人,并且将对应的
SELECT distinct s_id
FROM score
)
-- 5、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
SELECT a.s_id AS '学生编号',a.s_name AS "学生姓名",COUNT(b.c_id) AS '选课总数',SUM(b.s_score) AS '总成绩'
FROM student a
JOIN score b on a.s_id = b.s_id
GROUP BY a.s_id,a.s_name
-- 6、查询"李"姓老师的数量
SELECT COUNT(t_id)
FROM teacher
WHERE t_name LIKE '李%'
-- 7、查询学过"张三"老师授课的同学的信息
SELECT a.*
FROM student a
JOIN score b on a.s_id = b.s_id
WHERE b.c_id in (
SELECT c_id
FROM course
WHERE t_id =(
SELECT t_id
FROM teacher
WHERE t_name = '张三'
))
-- 8、查询没学过"张三"老师授课的同学的信息
SELECT *
FROM student s
WHERE s.s_id not in (
SELECT a.s_id
FROM student a
JOIN score b on a.s_id = b.s_id
WHERE b.c_id IN(
SELECT c_id
FROM course
WHERE t_id = (
SELECT t_id
FROM teacher
WHERE t_name = '张三'
)
)
)
-- 9、查询学过编号为"01"并且也学过编号为"02"的课程的同学的信息
SELECT a.*
FROM student a,score b,score c
WHERE a.s_id = b.s_id AND a.s_id = c.s_id AND b.c_id = '01' AND c.c_id = '02'
-- 10、查询学过编号为"01"但是没有学过编号为"02"的课程的同学的信息
SELECT a.*
FROM student a
WHERE a.s_id in (
SELECT s_id
FROM score
WHERE c_id = '01'
)
AND a.s_id not in (
SELECT s_id
FROM score
WHERE c_id = '02'
)
-- 11、查询没有学全所有课程的同学的信息
select s.*
from student s
where s.s_id in(
select s_id from score where s_id not in(
select a.s_id
from score a
join score b on a.s_id = b.s_id and b.c_id='02'
join score c on a.s_id = c.s_id and c.c_id='03'
where a.c_id='01'))
-- 12、查询至少有一门课与学号为"01"的同学所学相同的同学的信息
SELECT s.*
FROM student s
WHERE s.s_id in(
SELECT DISTINCT s_id
FROM score
WHERE c_id in (
SELECT a.c_id
F
mysql 语句练习笔记
最新推荐文章于 2020-12-18 18:12:39 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)