mysql 的 join 和 where 优先级

    技术2022-07-16  90

    mysql 的 join 和 where 优先级

    定义

    join功能

    inner join(内连接,或等值连接) : 获取两个表中字段匹配关系的记录。left join (左连接) : 获取左表所有记录,即使右表没有对应匹配的记录。right join (右连接) : 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。

    where

    where 是 mysql 语句的查询条件

    测试数据表

    表 a1

    xy110220330

    表 a2

    xy101002020020300 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; xyyz110101002202020022020300330NULLNULL

    左连情况下, 由于左边a1.y = 30在右表无数据所以右表数据 (y,z)为 NULL

    左连 on && and

    select * from a1 left join a2 on a1.y = a2.y and a2.y = 10; xyyz11010100220NULLNULL330NULLNULL

    由于是左连, 所以判断 (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; xyyz11010100

    只有一条数据, 因此可判断其优先级为select * from (a1 left join a2 on a1.y = a2.y) where a2.y = 10. 也就是说 会先左连生成临时表, 然后再在整体表上进行 where 查询.

    Processed: 0.013, SQL: 9