背景:学分查询系统
关系表设计思想:创建联系,老师和学生的对应关系 多对多,一个老师教多个学生,一个学生也有多个老师;
1. 建立关联表:组合表关联老师表 、组合表关联学生表 ;分别 通过teacher_id、 student_id 关联
---左关联用法: 表2名 left jion 表1名 on
SELECT
*
FROM
`union`
LEFT JOIN student ON `union`.student_id = student.student_id
LEFT JOIN teacher ON `union`.teacher_id = teacher.teacher_id
WHERE
sname in("黎明")
2. 建立关联表:分数表、学生表通过 student_id 关联
---左关联用法: 表2名 left jion 表1名 on
SELECT
*
FROM
student
LEFT JOIN score ON student.student_id = score.student_id
WHERE
cname IN("语文")
要求:
1. 查询学生信息
2. 查询教师信息
SELECT * FROM `student`;
SELECT * FROM `teacher`
3.查询某个学生的授课教师
SELECT
sname,tname
FROM
`union`
LEFT JOIN student ON `union`.student_id = student.student_id
LEFT JOIN teacher ON `union`.teacher_id = teacher.teacher_id
WHERE sname in("黎明");
-- 4.查询某个老师的带了多少学生-----------------------------------------
SELECT
tname,
COUNT(*) as student_num
FROM
`union`
LEFT JOIN student ON `union`.student_id = student.student_id
LEFT JOIN teacher ON `union`.teacher_id = teacher.teacher_id
WHERE tname in("赵宗");
--- 5.查询某个学生的每门课程的分数--------------------------------------
SELECT
sname,cname,score
FROM
score
LEFT JOIN student ON student.student_id = score.student_id
WHERE sname in("黎明")
--=6.查询学生的某一个科目的平均分,及格率-------------------------------
SELECT
cname, AVG( score ) AS 平均分,
SUM( CASE WHEN score >= 60 THEN 1 ELSE NULL END ) / count(*) AS "及格率"
FROM
student
LEFT JOIN score ON student.student_id = score.student_id
WHERE
cname IN ( "语文" )
注:sum (Case when score >= 60 then 1 else null end)
表示大于等于60分记作1 否则为null, 的个数