多表关联 join
关联逻辑,会根据on条件,一条一条进行对比,只显示满足on条件的数据。
# join关联 先使用on条件筛选两表数据,然后在生成一张新表
源数据
student
| id | name |
|---|---|
| 1 | 张三 |
| 2 | 李四 |
| 3 | 王二麻子 |
student_score
| student_id | course | score |
|---|---|---|
| 2 | 语文 | 80 |
| 3 | 语文 | 85 |
| 4 | 语文 | 90 |
内连接-inner join
select * from student a inner join student_score b on a.id = b.student_id;
两表数据只显示满足on条件的

左连接-left join
select * from student a left join student_score b on a.id = b.student_id;
左表数据库为主表,左表数据全部显示,右表只显示满足on条件的,不满足条件的数据显示为null
| id | name | student_id | course | score |
|---|---|---|---|---|
| 1 | 张三 | null | null | null |
| 2 | 李四 | 2 | 语文 | 80 |
| 3 | 王二麻子 | 3 | 语文 | 85 |
右连接-right join
select * from student a right join student_score b on a.id = b.student_id;
右表数据库为主表,右表数据全部显示,左表只显示满足on条件的,不满足条件的数据显示为null
| id | name | student_id | course | score |
|---|---|---|---|---|
| 2 | 李四 | 2 | 语文 | 80 |
| 3 | 王二麻子 | 3 | 语文 | 85 |
| null | null | 4 | 语文 | 90 |
全连接-full join
select * from student a full join student_score b on a.id = b.student_id;
两个表中的数据全部显示,不满足on条件显示为null
| id | name | student_id | course | score |
|---|---|---|---|---|
| 1 | 张三 | null | null | null |
| 2 | 李四 | 2 | 语文 | 80 |
| 3 | 王二麻子 | 3 | 语文 | 85 |
| null | null | 4 | 语文 | 90 |

注意:
- join 关联和where关联的区别
- 左连接,右连接,内连接,全连接的区别


