mysql 的 join 和 where 優先級
定義
join功能
- inner join(內連接,或等值連接) : 獲取兩個表中字段匹配關係的記錄。
- left join (左連接) : 獲取左表所有記錄,即使右表沒有對應匹配的記錄。
- right join (右連接) : 與 LEFT JOIN 相反,用於獲取右表所有記錄,即使左表沒有對應匹配的記錄。
where
where 是 mysql 語句的查詢條件
測試數據表
表 a1
x | y |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
表 a2
x | y |
---|---|
10 | 100 |
20 | 200 |
20 | 300 |
create table if not exists `a1`(
`x` int(10),
`y` int(10)
);
create table if not exists `a2`(
`y` int(10),
`z` int(10)
)
查詢 sql 及結果
正常左連接
select * from a1 left join a2 on a1.y = a2.y;
x | y | y | z |
---|---|---|---|
1 | 10 | 10 | 100 |
2 | 20 | 20 | 200 |
2 | 20 | 20 | 300 |
3 | 30 | NULL | NULL |
左連情況下, 由於左邊a1.y = 30在右表無數據所以右表數據 (y,z)爲 NULL
左連 on && and
select * from a1 left join a2 on a1.y = a2.y and a2.y = 10;
x | y | y | z |
---|---|---|---|
1 | 10 | 10 | 100 |
2 | 20 | NULL | NULL |
3 | 30 | NULL | NULL |
由於是左連, 所以判斷 (a1.y = a2.y && a2.y = 10) 只能篩選出(10, 100)與左邊匹配, 所以後面均爲 NULL.
即實際優先級是 select * from (a1 left join a2 on a1.y = a2.y and a2.y = 10)
左連 on && where
select * from a1 left join a2 on a1.y = a2.y where a2.y = 10;
x | y | y | z |
---|---|---|---|
1 | 10 | 10 | 100 |
只有一條數據, 因此可判斷其優先級爲select * from (a1 left join a2 on a1.y = a2.y) where a2.y = 10
.
也就是說 會先左連生成臨時表, 然後再在整體表上進行 where 查詢.