假设有以下两张表:
学校表(tbl_school):
| ID | 学校名称(school_name) |
| 1 | 长乐一中 |
| 2 | 长乐二中 |
| 3 | 长乐三中 |
学生表(tbl_student):
| ID | 学生姓名(student_name) | 所属学校(school_id) |
| 1 | 张三 | 1 |
| 2 | 李四 | 2 |
| 3 | 王五 | 1 |
1. inner join
select t1.school_name schoolName, t2.student_name studentName
from tbl_school t1
inner join tbl_student t2 on t1.id = t2.school_id
order by t1.id
| schoolName | studentName |
| 长乐一中 | 张三 |
| 长乐一中 | 王五 |
| 长乐二中 | 李四 |
inner join的inner可省略
2. left join
select t1.school_name schoolName, t2.student_name studentName
from tbl_school t1
left join tbl_student t2 on t1.id = t2.school_id
order by t1.id
| schoolName | studentName |
| 长乐一中 | 张三 |
| 长乐一中 | 王五 |
| 长乐二中 | 李四 |
| 长乐三中 | NULL |
3. right join
select t1.school_name schoolName, t2.student_name studentName
from tbl_student t2
right join tbl_school t1 on t1.id = t2.school_id
order by t1.id
| schoolName | studentName |
| 长乐一中 | 张三 |
| 长乐一中 | 李四 |
| 长乐二中 | 王五 |
| 长乐三中 | NULL |
可以看出来right join 跟left join差不多。。看个人习惯用哪个
SQL连接类型详解
本文通过具体实例详细介绍了SQL中三种连接类型:内连接(inner join)、左连接(left join)及右连接(right join)的使用方法及区别。展示了如何从两个关联表中提取数据,并对比了不同连接方式下数据返回的结果。
4524

被折叠的 条评论
为什么被折叠?



