一.關鍵字
左連接配接:以左邊的表為參照,顯示所有資料,如右表中沒有則以null顯示
關鍵字:left join
右連接配接:以右邊的表為參照,顯示所有資料,如左表中沒有則以null顯示
關鍵字:right join
二.先簡單的建立兩張簡單的表格
table1
grade | id | number |
---|---|---|
四年級 | 1 | 200 |
五年級 | 2 | 300 |
六年級 | 3 | 400 |
table2
name | ClassId | age | class |
---|---|---|---|
小明 | 1 | 11 | 1班 |
小紅 | 2 | 12 | 4班 |
小剛 | 4 | 13 | 2班 |
三.代碼示範
1)以table1表進行左連接配接(left join):
/*T1 T2為取别名,可以直接利用 别名.字段 進行查詢*/
select * from table1 T1 left join table2 T2 on T1.id= T2.ClassId ;
查詢結果:
id | grade | number | name | age | class |
---|---|---|---|---|---|
1 | 四年級 | 200 | 小明 | 11 | 1班 |
2 | 五年級 | 300 | 小紅 | 12 | 4班 |
3 | 六年級 | 400 | null | null | null |
2)以table1表進行右連接配接(right join):
/*T1 T2為取别名,可以直接利用 别名.字段 進行查詢*/
select * from table1 T1 right join table2 T2 on T1.id= T2.ClassId ;
查詢結果:
id | grade | number | name | age | class |
---|---|---|---|---|---|
1 | 四年級 | 200 | 小明 | 11 | 1班 |
2 | 五年級 | 300 | 小紅 | 12 | 4班 |
4 | null | null | 小剛 | 13 | 2班 |