mysql 的 join 和 where 优先级

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 查询.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章