學生表(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 | 西安交通大學 |