zoukankan      html  css  js  c++  java
  • mysql语句执行顺序

    思考:

    大家可以思考一下下面sql语句写的有没有问题?

    select jg.id as goodsId,jm.name,...
    from jdy_merchant jm
    left outer join jdy_express_template jet on jet.id = jg.freight
    left outer join jdy_goods jg on jm.id = jg.store_id
    where jg.id = 1

    甭管有没有,运行一下见分晓:

     Unknown column 'jg.freight' in 'on clause'

    嗯哼? 问题来了,表里明明有这个字段为什么还会找不到这一列呢?

    这里就要说一下sql查询语句的执行顺序问题了:

    分析:

    sql查询语句中的执行顺序为:

    from : 从哪个表查询数据 必须关键字
    
    on : 关联条件
    
    join : 关联表
    
    where : 过滤条件
    
    group by : 将过滤后的数据进行分组
    
    having : 将分组后的数据再次进行过滤
    
    select :查询的列
    
    order by : 将最终的查询结果进行排序
    
    最后将查询的结果进行返回

    接下来分析下上面的语句:

    执行from 关联的表,这里有三个表,jdy_merchant jm,jdy_express_template jet,jdy_goods jg 

    这三张表是按on指定的条件将left join后面的表附加到前面表之后的,

    第一张表肯定没有问题,到left outer join jdy_express_template jet on jet.id = jg.freight这一句的时候就出现问题了

    大家看一下关联条件 jet.id = jg.freight ,这时候前面还没有jdy_goods jg这张表,所以引用jg.freight就报错了

    怎么改呢:

    把关联表颠倒一下顺序就可以了,像这样:

    select jg.id as goodsId,jm.name
    from jdy_merchant jm
    left outer join jdy_goods jg on jm.id = jg.store_id
    left outer join jdy_express_template jet on jet.id = jg.freight
    where jg.id = 1

    执行结果:

                                                                    

                                                                       自己挖的坑哭着也要填完

        END !!!

      

  • 相关阅读:
    hdu 5366 简单递推
    hdu 5365 判断正方形
    hdu 3635 并查集
    hdu 4497 数论
    hdu5419 Victor and Toys
    hdu5426 Rikka with Game
    poj2074 Line of Sight
    hdu5425 Rikka with Tree II
    hdu5424 Rikka with Graph II
    poj1009 Edge Detection
  • 原文地址:https://www.cnblogs.com/aigezi/p/12859015.html
Copyright © 2011-2022 走看看