mysql中的join和where优先级顺序是什么

数据库   发布日期:2023年09月11日   浏览次数:217

这篇“mysql中的join和where优先级顺序是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“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 查询.

    以上就是mysql中的join和where优先级顺序是什么的详细内容,更多关于mysql中的join和where优先级顺序是什么的资料请关注九品源码其它相关文章!