现在的位置: 首页 > 综合 > 正文

数据库多表连接

2018年04月01日 ⁄ 综合 ⁄ 共 573字 ⁄ 字号 评论关闭

在开始复习数据库的多表连接之前,先来看一个例子。假设数据库有以下的表:

courses: courseId*, courseName, teacherId

teachers:teacherId*,teacherName

students:studentsId*,studentName

studentCourses: courseId*, studentId*(以上带*的字段表示主键)


查询:学生选课情况


实现一个查询,列出所有的学生,以及每个学生选修了几门课程。可能开始我们会这样写:
select A.students, count(*) from students A, studentCourses B where A.studentsId=B.studentsId。
其实这条语句有几个错误,首先,表的连接关系出错。本条语句采用了内连接,会将未选课的学生信息给过滤掉。
数据库的表连接分为内连接和外连接。

内连接


内连接有显式连接和隐式连接写法。上述的写法就是内连接的隐式连接写法。它等价于:
select A.students,count(*) from students A inner join B on A.studentsId=B.studentsId.
studentId studentName
10101 张三
10102 李四

studentId courseId
10101 4
10101 2

查询的结果为:

抱歉!评论已关闭.