sql中right join和left join如何在效果相同的情況下實現互換?
- 2021-10-16
select * from table1 right join table2 on 關聯條件
與
select * from table2 left join table1 on 關聯條件
這2個一樣
select * from table1 right join table2 on 關聯條件 right join table3
on 關聯條件
與
select * from table3 left join table2 on 關聯條件 left join table1
on 關聯條件
這2個不一樣,前者要看2個關聯條件而定,後者就是以table3為主表的
left join是以左表為準的。
左表(a)的記錄將會全部表示出來,而右表(b)只會顯示符合搜尋條件的記錄(例子中為: a。aid = b。bid)。
b表記錄不足的地方均為null。
ps:right join表理解相同
官方的解釋下:
inner join(等值連線):只返回兩個表中聯結欄位相等的行;
left join(左聯接):返回包括左表中的所有記錄和右表中聯結欄位相等的記錄;
right join(右聯接):返回包括右表中的所有記錄和左表中聯結欄位相等的記錄。
比如我們有xs、cj兩個表
xs表 cj表
————————- ————————————
id name id score
1 張三 1 96
2 李四 2 80
3 86
sql程式碼 1。
select
*
from
`xs`
inner
join `cj`
on
xs。id = cj。id select * from `xs` inner join `cj` on xs。id = cj。id
返回
————————————
id name id score
1 張三 1 96
2 李四 2 80
————————————-
sql程式碼 1。
select
*
from
`xs` left join `cj`
on
xs。id = cj。id select * from `xs` left join `cj` on xs。id = cj。id
返回
————————————
id name id score
1 張三 1 96
2 李四 2 80
————————————-
sql程式碼 1。
select
*
from
`xs` right join `cj`
on
xs。id = cj。id select * from `xs` right join `cj` on xs。id = cj。id
返回
id name id score
1 張三 1 96
2 李四 2 80
null null 3 86
select * from table1 right join table2 on 關聯條件 right join table3
on 關聯條件
相同
建議樓主使用時加上()括號,便於自己檢視邏輯