SQL Joins Explained with Tables
Let’s consider three tables: 学生
, 选课
, and 课程
.
学生表 (Students)
学号 (ID) | 姓名 (Name) |
---|---|
1 | 张三 |
2 | 李四 |
3 | 王五 |
选课表 (Course Selections)
选课ID | 学号 (Student ID) | 课程编号 (Course ID) |
---|---|---|
1 | 1 | 101 |
2 | 1 | 102 |
3 | 2 | 101 |
课程表 (Courses)
课程编号 (ID) | 课程名称 (Name) |
---|---|
101 | 数学 |
102 | 物理 |
103 | 化学 |
Now, let’s look at different types of joins:
1. INNER JOIN
sql
1 | SELECT 学生.姓名, 课程.课程名称 |
Result:
姓名 | 课程名称 |
---|---|
张三 | 数学 |
张三 | 物理 |
李四 | 数学 |
Explanation: This returns only the rows where there’s a match in all three tables.
2. LEFT JOIN
sql
1 | SELECT 学生.姓名, 课程.课程名称 |
Result:
姓名 | 课程名称 |
---|---|
张三 | 数学 |
张三 | 物理 |
李四 | 数学 |
王五 | NULL |
Explanation: This returns all students, even if they haven’t selected any courses.
3. RIGHT JOIN
sql
1 | SELECT 学生.姓名, 课程.课程名称 |
Result:
姓名 | 课程名称 |
---|---|
张三 | 数学 |
张三 | 物理 |
李四 | 数学 |
NULL | 化学 |
Explanation: This returns all courses, even if no student has selected them.
4. FULL OUTER JOIN
sql
1 | SELECT 学生.姓名, 课程.课程名称 |
Result:
姓名 | 课程名称 |
---|---|
张三 | 数学 |
张三 | 物理 |
李四 | 数学 |
王五 | NULL |
NULL | 化学 |
Explanation: This returns all rows from all tables, using NULL where there is no match.