优化器会根据实际语句优化,我见过一个例子,3个表关联,当你需要查两个表的数据时,执行计划会关联3表,但是把select中的列限制到一个表的列时,它就把其中一个表去掉,实际上之关联两个表

解决方案 »

  1.   

    为什么会不一样呢。虽然看着都是left join ,但是:1.left join 把(LStationID is null or LStationID = 'KDDG00001890')条件写到了on条件后。2.left join中把(LStationID is null or LStationID = 'KDDG00001890')写到了where后面,这样sql server就会自动把left join 转化为inner join。也就是这样:--这个还是left join
    select *
    from a 
    left join b
           on a.id = b.id and b.xxx = 'xxx'
    --这个就是转化为inner join
    select *
    from a 
    left join b
           on a.id = b.id 
    where b.xxx = 'xxx'
      

  2.   

    所以,如果你是left  join 那么最好是把关联条件写到 on后面,因为写到where 后面,其实从语义的角度,就已经转化为inner join了,因为这样也是一样的:select *
    from a
    inner join b
            on a.id = b.id等价于:select *
    from a,b
    where a.id = b.id。做了一个例子,你可以参考参考:drop table a,B
    gocreate table a(id int)insert into a
    select 1 union all
    select 2create table b(id int,xxx varchar(10))insert into b
    select 1,'xxx' union all
    select 2,'xx'
    go
    --这个还是left join
    select *
    from a 
    left join b
           on a.id = b.id and b.xxx = 'xxx'
    /*
    id id xxx
    1 1 xxx
    2 NULL NULL
    */ 
     select * --这个就是转化为inner join
    from a 
    left join b
           on a.id = b.id 
    where b.xxx = 'xxx'
    /*
    id id xxx
    1 1 xxx
    */
      

  3.   

    原来是这么一回事。。好复杂。就是说 left join 的条件都不要放到 where 后面啦
      

  4.   


    嗯,对的,left join的就放on后面
      

  5.   

    on后面是关联条件,where的才是筛选条件
      

  6.   

    如果这样说,他应该将我 null 的记录也查询出来吧。
      

  7.   

    如果这样说,他应该将我 null 的记录也查询出来吧。是被左联的表,的条件写在on 后面,比如:select *
    from a
    left join b
           on a.id = b.id and b.xxx = xxx
    where a.xxx = xxx对b的过滤条件可以写在on后面,而a表的过滤条件,可以写在on后面,也可以写在where 后面
      

  8.   

    如果这样说,他应该将我 null 的记录也查询出来吧。是被左联的表,的条件写在on 后面,比如:select *
    from a
    left join b
           on a.id = b.id and b.xxx = xxx
    where a.xxx = xxx对b的过滤条件可以写在on后面,而a表的过滤条件,可以写在on后面,也可以写在where 后面
    测试了下,对a表的过滤只能写在 where 后面。left join 的 on 只能对右表起作用。
    这个完全颠覆了我对 join 的认识,不知道如何是好,因为有的left join 是写在视图的。够晕的啦
      

  9.   

    如果这样说,他应该将我 null 的记录也查询出来吧。是被左联的表,的条件写在on 后面,比如:select *
    from a
    left join b
           on a.id = b.id and b.xxx = xxx
    where a.xxx = xxx对b的过滤条件可以写在on后面,而a表的过滤条件,可以写在on后面,也可以写在where 后面
    测试了下,对a表的过滤只能写在 where 后面。left join 的 on 只能对右表起作用。
    这个完全颠覆了我对 join 的认识,不知道如何是好,因为有的left join 是写在视图的。够晕的啦a的过滤条件,可以写在on或者where的后面,但是left join的条件,的写在on后面
      

  10.   

    on 是连接条件 ;where 是过滤条件。
      

  11.   

    呵呵,其实问题是
    FROM #tmp gx left join SF_GXShangChuan a on gx.GXMXID=a.GXMXSID
    已经包含全部数据了,所以,只能将a表的条件放到 on 后面。
    谢谢大家,长见识了。
    另外还知道 left join 是首先为 on 的条件生成临时表,之后再将没有的数据加入到临时表。