使用left join即可。table1中不存在于table2中的user_id在table2的user_id字段将会是null,然后对table2的user_id字段过滤以下即可。具体sql语句如下:select a.user_id,b.user_id as temp from table1 a left join table2 b on a.user_id=b.user_id and b.b_id=20 having temp is null

解决方案 »

  1.   

    解释一下上面的sql语句:
    select a.user_id,b.user_id as temp #选取两个表中的user_id
    from table1 a left join table2 b # LEFT JOIN是什么意义呢?属于基础知识
    on a.user_id=b.user_id # 最简单的联合查询条件
    and b.b_id=020 # 只需要020下面的user_id
    having temp is null # 将left join后的结果过滤一下,去掉table2中非null(也就是user_id存在于table2的行)
      

  2.   

    楼上的弄反了,select b.user_id 
    from table2
    left join table1 on table2.user_id=table1.user_id
    where table2.b_id=020 and table1.user_id is null
      

  3.   

    ice_berg16(寻梦的稻草人)   
                              的是正解那么楼主为什么不用not in呢?  
    讲起速度和效果来差不多的啊
      

  4.   

    先谢谢上面的各位;昨晚回去用上面的查询,不管是左联还是内联,都会出现数据库忙,读不出数据(可能是记录大多了吧,每个表大概有200万)
    后来我用两条查询来实现的,大意如下:
    select user_id from table2 where b_id=020
    得出数组A,user_id数符串str;
    select user_id from table1 where user_id in (str)
    得出数组B
    $result = array_diff (A, B);是我要得到的数据。说明下,数组A最多是200个user_id左右,所以第二条查询可能快点。
    但也没有真正比较查询时间,希望大家继续讨论下,能否有更好的解决方法。
      

  5.   

    left join的效率在大多数情况下比inner join要低的多
    所以除非不得已,还是少用的好
    不过楼主说"不管是左联还是内联,都会出现数据库",那么你给某些字段加过索引吗
      

  6.   

    有索引,但不是user_id和b_id这两个字段。像这样查的不多,所以没有建
      

  7.   

    记录这么多的话还是建一个索引吧,
    b_id和user_id的多列索引
      

  8.   

    select a.user_id from table1 as a,table2 as b where a.b_id=020 and a.user_id <> b.user_id这样行吗?
      

  9.   

    搞反了 :(select b.user_id from table1 as a,table2 as b where b.b_id=020 and a.user_id <> b.user_id