例子
现在有3个表,按下图的方式连接。
- 查询每个学生每个科目的分数
分析:学生姓名在students表,科目名在subjects表,分数则在scores表,如何查询呢?
这里就要使用连接查询了
我们希望的显示效果是这样的:
xxx(name) | yyy(科目) | zzz(分数)
students.name | subjects.title | scores.score
join后面写的是表名,on后面写的是关系
select students.name, subjects.title, scores.score
from scores
innner join students on scores.stuid=students.id
innner join subjects on scores.subid=subjects.id
另一种写法,从students表查询
select students.name, subjects.title, scores.score
from students
innner join scoreson scores.stuid=students.id
innner join subjects on scores.subid=subjects.id
结论:当需要对有关系的多张表(需要的信息来自多张表)进行查询时,需要使用连接join。
连接查询的类型
有以下几种类型:
- 表A inner join 表B:表A与表B匹配的行会出现在结果中
- 表A left join 表B:表A与表B匹配的行会出现在结果中,外加表A中独有的数据,未对应的数据使用null填充
- 表A right join 表B:表A与表B匹配的行会出现在结果中,外加表B中独有的数据,未对应的数据使用null填充
例如:
select * from students left join scores on students.id=scores.stuid
(left和right就是指命令中 写在左边的表和右边的表)
前面几行信息完整的数据,就是两个表可以匹配上的数据。后面的3行,这3个人在scores里没有分数,所以他们的信息用null填充。因为是left,所以以左表(students)为准。
使用right join 的例子:
select * from scores right join students on scores.stuid=students.id