现在有两个表,都有10万条记录A表
--------------------
id name age sexB表
-----------------------
id address phone birth其中B表中的ID集合,是A表ID的子集。
现在要执行如下语句:
select count(*) from A where id in (select id from B)发现效率很低,怎么改比较好。各位兄弟给点建议,多谢!

解决方案 »

  1.   

    更复杂一些的查询
    select count(*) from A where and age>18 and age<60 and id in (select id from B)
      

  2.   

    1.不要用in,用exists;
    2.对经常出现在条件中的非主键字段,比如age,建索引;
      

  3.   

    select count(*) from A,b where A.id =B.ID
      

  4.   

    刚刚使用exists替换in,性能提高30%,真不错。
    还有别的方法吗?
      

  5.   

    谢谢doer_ljy 兄弟,可能您的方法不适合我的情况,刚实验了一下您的方法,提高不多
      

  6.   

    需要查询的字段建立索引
    然后用inner join来查询
      

  7.   

    select count(A.ID) from A,b where A.id =B.ID
      

  8.   

    这个应用可能不需要inner join;
    select * from a,b where a.id=b.id在我的应用中好像效率有限。
      

  9.   

    使用表关联。SELECT COUNT(a.id) FROM A AS a,B AS b WHERE a.id = b.id;
      

  10.   

    楼上兄弟,这两个表,行数很多。使用WHERE a.id = b.id;不能改善效率。
    经测试exists子句确实效率更高。
      

  11.   

    对于IN语句,需要消耗大量的CPU。
    一般采用“联机视图”来替代“IN”操作。语法如下:
    select count(*) from A,(select id from B) x
    where A.ID = x.ID
      and ...其中select id from b为联机视图,你可以在这里添加各种条件。
      

  12.   

    问楼主,如果换用exists子句,该怎么写
      

  13.   

    楼主,如果你在两个表的id上都建立了索引,那么利用表关联的方法应该比exists更有效才对啊
      

  14.   

    肯定是内连接from A,b where A.id =B.ID
    其次是exists语句的效率是最高的。
    这种数据量的情况下,不要用in去实现,效率太差。
    如果你的内存够大的话,内连接会比exists效率高很多。
      

  15.   

    select count(*) from A aaa where exists ( select null from B bbb where bbb.id = aaa.Business_ID )
      

  16.   

    select count(*) from A aaa where exists ( select null from B bbb where bbb.id = aaa.id)
      

  17.   

    很难理解,自己从没有遇到过使用内连接性能低于exists的例子。
    在我本地的测试中楼上的sql是要经历两个Table Access Full的。
    而是用等值连接只需要对较小的表作一个Table Access Full,对另一个表则是by index的。
    希望楼主能贴出两种SQL的执行计划作进一步分析。