1 查询时要用到的表以及表中数据
(1)学生表(student) 表中的数据如下: (2)课程表(course) 表中的数据如下: (3)教师表(teacher) 表中数据如下: (4)成绩表(score) 表中数据如下: (5)教师—课程表(teach) 表中无数据。
表之间的关系: 1、学生与课程之间是多对多(m:n)的关系:一名学生要学习多门课程,一门课程有多名学生学习。 2、教师与课程之间是多对多(m:n)的关系:一个老师可以上多门课程,一门课程可以由多个老师上
2 实例
1、查询"01"课程比"02"课程成绩高的学生的信息及课程分数
SELECT
a.*,
b.s_score AS "语文",
c.s_score AS "数学"
FROM
student AS a,
score AS b,
score AS 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"
AND b.s_score > c.s_score;
SELECT
a.*,
b.s_score AS "语文",
c.s_score AS "数学"
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;
注意: 1、join表示连接,与on连用,on后面加连接的条件 2、left join表示左连接,左表中的信息全部显示出来,再把符合条件的信息显示出来
2、查询所有同学的学生编号、学生姓名、选课总数、所有课程的总成绩
SELECT
a.s_id,
a.s_name,
COUNT( b.c_id ) AS "选课总数",
SUM( b.s_score ) AS "总成绩"
FROM
student a
LEFT JOIN score b ON a.s_id = b.s_id
GROUP BY
a.s_id;
3、查询"李"姓老师的数量
SELECT
COUNT( t_id )
FROM
teacher
WHERE
t_name LIKE "李%";
|