select * from a where EXP_CODE='R8_002_XZ' and code not in (select code from b)=======================================================select * from a left join b on a.code=b.code
  where a.EXP_CODE='R8_002_XZ' and b.code is null再看你的code上有无索引,如无,建索引, exp_code 上也建

解决方案 »

  1.   

    楼上正解,但是对于百万条记录数据库还是慢的,可以用limit限定
      

  2.   

    谢谢 helloyou0
    用你的代码效率的确太高了,但在执行过程中又出的个问题
    如果a表中有多条记录的CODE 相同,但EXP_CODE不同,执行后只会显示其中一条记录如:
    a表中有:
      CODE    EXP_CODE
    123456    R8_002_XZ
    123456    R8_002b表中有:
      CODE    EXP_CODE
     123456   R8_002_XZ如果查询:
    select * from a left join b on a.code=b.code where a.EXP_CODE='R8_002' and b.code is null
    将无法得到123456    R8_002 的记录
      

  3.   

    你不是要找expcode等于r8_002_xz的纪录吗?
      

  4.   

    是不唯一,看似简单,其实很有难度,思路是这样的一、A表为主表,包含所有记录。要找出其EXP_CODE='R8_002_XZ' 的记录。二、找出B表中EXP_CODE!='R8_002_XZ' and a.CODE!=b.CODE也就是说要找出A、B两表中CODE和EXP_CODE同时不相同的记录。但如果简单的用
    $sql="select * from a,b where a.CODE!=b.CODE and a.EXP_CODE!=b.EXP_CODE and a.CODE='R8_002_XZ'";找出的记录会是一个无限循环
      

  5.   

    select * from a where exp_code='r8_002_xz' and code not exist(select code from b where exp_code!='r8_002_xz')
    上面的语法可能有点问题,但是逻辑关系应该是对的.
    要求:version>4.1,支持子查询.
      

  6.   

    这个是你要的吗
    select * from a left join b on a.code=b.code and a.EXP_CODE=b.EXP_CODE
     where a.EXP_CODE='R8_002' and b.code is null
      

  7.   

    嵌套的select效率比较低,尽量用inner join, left join代替
      

  8.   

    上面写错了.改成以下:
    select * from a where exp_code='r8_002_xz' and code not in(select code from b where exp_code!='r8_002_xz');
    或者
    select * from a where exp_code='r8_002_xz' and not exists(select code from b where exp_code!='r8_002_xz' and a.code=b.code);
      

  9.   

    select * from a left join b on a.code=b.code and a.EXP_CODE=b.EXP_CODE and b.code is null你只需要找出a中有而b中没有的记录,然后按b的结构追加就可以了!辛苦了,"农普"同行!