连接
- 我们先来看一个问题,查询每个学生的每个科目的分数
- 学生姓名来源于students表,科目名称来源于subjects表,分数来源于scores表。如何将三个表放在一起查询呢?并将结果显示在同一个结果集中。
- 答:当查询结果来源于多张表时,我们需要使用 连接查询
关键找到表之间的关系,当前的关系是
- students表的 id – scores 表的 stuid
- subjects表的 id – scores 表的 subid
则上面问题的答案是
1
2
3
4select students.sname,subjects.stitle,scores.score
from scores
inner join students on scores.stuid=student.id
inner join subjects on scores.subid=subjects.id;查询男生的姓名,平均分
1
2
3
4
5select students.sname,ave(scores.score)
from scores
inner join students on score.stuid=student.id
where students.gender=1
group by students.sname;