学生表(student)
studentId | name | phone | collegeId |
---|---|---|---|
1 | 张三 | 18320931475 | 1 |
2 | 李四 | 17745203643 | 2 |
3 | 王五 | 15532840263 | 3 |
学校表(college)
collegeId | collegeName |
---|---|
1 | 长安大学 |
2 | 复旦大学 |
3 | 西北政法大学 |
4 | 西安交通大学 |
多表联查
SELECT a.studentId,a.name,a.phone,b.collegeName FROM `student` AS a JOIN college AS b ON a.collegeId = b.collegeId
// 将student表暂存为a,college表暂存为b,
// 用student表中的collegeId在college表中查询college表中的数据,
// 结果表中显示的是select后面的内容(student中的id,name,phone,college表中的collegeName)
查询结果
studentId | name | phone | collegeName |
---|---|---|---|
1 | 张三 | 18320931475 | 长安大学 |
2 | 李四 | 17745203643 | 复旦大学 |
3 | 王五 | 15532840263 | 西北政法大学 |
左外连接
// 左外链接
SELECT a.studentId,a.name,a.phone,b.collegeName FROM `student` AS a LEFT OUTER JOIN college AS b ON a.collegeId = b.collegeId
// 以JOIN左边的表为主表,将左边表中的数据显示完全即结束显示,当右表中没有对应数据时,结果表中的右表项目会显示为NULL
查询结果
studentId | name | phone | collegeName |
---|---|---|---|
1 | 张三 | 18320931475 | 长安大学 |
2 | 李四 | 17745203643 | 复旦大学 |
3 | 王五 | 15532840263 | 西北政法大学 |
右外连接
// 右外连接
SELECT a.studentId,a.name,a.phone,b.collegeName FROM `student` AS a RIGHT OUTER JOIN college AS b ON a.collegeId = b.collegeId
// 以JOIN右边的表为主表,将右边表中的数据显示完全即结束显示,当左表中没有对应值时,结果表中的左表项目会显示为NULL
查询结果
studentId | name | phone | collegeName |
---|---|---|---|
1 | 张三 | 18320931475 | 长安大学 |
2 | 李四 | 17745203643 | 复旦大学 |
3 | 王五 | 15532840263 | 西北政法大学 |
NULL | NULL | NULL | 西安交通大学 |