select a.* from a left join b on a.iid=b.iid where a.iid not in(select distinct iid from c)select a.* from a left join b on a.iid=b.iid where not exists(select 1 from c where c.iid=a.iid)--上面两个语句具体的区别是什么?当C中没有数据时候结果都是正确的,但是但C中有数据是,第一种写法查询出来的数据是正确的,但是第二种写法就查不到数据了。--求高手详细的告诉我,最好教教我in、exists、not in、not exists的区别,谢谢了。

解决方案 »

  1.   

    有NULL值就不一样
    一般是效率问题,in ,not in 的效率比exists,not exists 效率低.
      

  2.   

    in/not in 我个人理解是在判断一列的时候用,但是有多列的时候,就不能in/not in了,exists /not exists可以在多列中使用,且只关系是否存在。
    另外你的例子中,第一个叫非关联子查询,第二个叫关联子查询。
      

  3.   

    in  跟exists没什么区别  区别主要是在于exists和not exists  而且是在存在空值的时候才会体现出来
      

  4.   


    我是想实现这样,
    A表
    iidB表
    iid 列2b 列3b 列4bC表
    iid 列2c 列3c 列4c三个表通过iid联,我想查询A表中iid对应于B表的列2b,列3b,列4b,但是这里面的iid不在C表里面。
    也就是说A表有C表没有的数据,查询的字段呢又在B表里面。请问要怎么写?
      

  5.   


    是啊当C表(临时表,里面的数据变动这)里面没有数据时,用not exists是对的,但是只要C有数据,就不对了,只能用 not in
      

  6.   


    存在null的时候建议使用not exists  这样结果准确  我不喜欢用in 和not in  效率上来说exists  和not exists有时候会高点  但不绝对
      

  7.   

    我是想实现这样,
    A表
    iidB表
    iid 列2b 列3b 列4bC表
    iid 列2c 列3c 列4c三个表通过iid联,我想查询A表中iid对应于B表的列2b,列3b,列4b,但是这里面的iid不在C表里面。
    也就是说A表有C表没有的数据,查询的字段呢又在B表里面。请问要怎么写?
      

  8.   

    我找出来了,我知道是哪里错了,就把c写成b了,B不是好东西啊
      

  9.   

    /*
    因为你的c表中iid字段存在null值,用in 或 not in时要注意这种情况。举例
    比如说: iid not in(1,2,null),相当于
    idd <> 1 and idd <> 2 and idd <> null
    而idd <> null 的结果是null,所以iid not in(1,2,null) 相当于 false忽略这种情况,逻辑上in, exists, not in, not exists是没有区别的。
    性能上的话,能用正向就不用反向查询,有索引的话用exists
    */
      

  10.   


    select 列2b,列3b,列4b from B表 a1
    where exists(select 1 from A表 a2 where a1.iid=a2.iid)
    and not exists(select 1 from C表 a3 where a.iid=a3.iid)说到底就是取B表的数据  只是要求iid在A表里面并且不再C表里面  是这个意思吧