兩張表,A表中的記錄B表中不一定有。
左連接:關注左邊,右邊沒有就為空。
右連接:關注右邊,左邊沒有就為空。
內連接:返回交集
例如:
student表s
id | name | age | class_id |
---|---|---|---|
1 | yang | 22 | 1 |
2 | su | 20 | 1 |
3 | fan | 20 | 2 |
4 | li | 30 | 2 |
5 | luo | 22 |
class表c
class_id | name | total |
---|---|---|
1 | 大一 | 30 |
2 | 大二 | 15 |
3 | 大三 | 40 |
在上面的表中,s表中的5號記錄在c表中是找不到數據的。
1.左連接,left join左邊為主要表,次表沒有對應的就顯示NULL。
SELECT s.`name`,s.`class_id` FROM student s LEFT JOIN class c ON s.`class_id`=c.`class_id`
結果
name | class_id |
---|---|
yang | 1 |
su | 1 |
fan | 2 |
li | 2 |
luo | (NULL) |
2.右連接,right jion右邊為主要表,次表沒有對應的就顯示NULL。
SELECT s.`name`,s.`class_id` FROM student s RIGHT JOIN class c ON s.`class_id`=c.`class_id`
結果
name | class_id |
---|---|
yang | 1 |
su | 1 |
fan | 2 |
li | 2 |
(NULL) | (NULL) |