一般是这样写select * from ta where id not in (select id from tb) 
这样的话,要先把所有的表B的值搞出来,然后再一个一个对比。
如果两个表都很大的话,那这效率是不是很低?

解决方案 »

  1.   

    这种查询对于小数据量还行,但是遇到大数据量就会发现你的IO读写非常频繁。
    exists和in都会发生Table Scan,我都不建议这样写,实现这个需求可以用join。
    例如楼主的语句:
    select * from ta where id not in (select id from tb)
    可以改成:
    select ta.* from ta left join tb on ta.id=tb.id where tb.id is null
      

  2.   

    如果是发生在insert,是不是只能用in,或者exist了?--假设TA,TB结构一样
    insert into TA
    select * from TB where TB.ID not in (selet id from TA)
    --或者
    insert into TA
    select * from TB where not exists (select 1 from TA where TA.ID=TB.ID)
    这样的语句,只能让数据库一条一条去比对了吧。
    没有更好的办法了吗?
      

  3.   


    当然不是,这两条记录一样可以改成join。
    insert into TA
    select TB.* from TB left join TA on TB.id=TA.id where TA.id is null
      

  4.   

    用 not exists
    100W的记录,用not in ,大概要30秒,用 not exists,只需要1秒不到
      

  5.   


    select * from ta where id not in (select id from tb) 
    UNION ALL
    select * from tb where id not in (select id from ta) 
      

  6.   


    测过才知道,通常not exists
    参考http://blog.csdn.net/orchidcat/article/details/6267552
      

  7.   

    最好的sql语句就是NOT IN ,然后加适合的INDEX就可以了。
    性能的好坏看计划,计划的本质是算法。1,严格来说NOT IN 跟not exists 不可相互代替,因为NOT IN 跟not exists 语义不同,也就是说可能会产生的不同的结果集合,。
    2,跟not exists 语义相同的是LEFT JOIN +IS NULL, 从算法上来看,not exists永远 >=LEFT JOIN +IS NULL
      

  8.   


    select * from ta a join tb b on a.id<>b.id
    我也请教一下,如果这样对不对呢?