现在有A、B、C三张表A(id,.....) A表的数据量:700W
B(id,.....) B表的数据量:200W
C(id,.....) C表的数据量:200Wid都是这三张表的主键1、查出A表的所有信息:条件id同时存在于B、C表select * from A where id in (select id from B where id in(select id from C));2、查出A表的所有信息:条件id存在于B但是不存在于C表select * from A where id in(select id from B where id not in(select id from c));这两句SQL语句应该如何优化?

解决方案 »

  1.   


    select * from A where id in (select id from B where id in(select id from C));
    ---->
    select * from a where exists (select id from (select id form b intersect select id from c) b where b.id =a.id)select * from A where id in(select id from B where id not in(select id from c));
    ----->
    select * from a where exists (select id from (select id form b minus select id from c) b where b.id =a.id)
      

  2.   

    用EXISTS替代IN、用NOT EXISTS替代NOT IN: 在许多基于基础表的查询中,为了满足一个条件,往往需要对另一个表进行联接.在这种情况下, 使用 EXISTS(或NOT EXISTS)通常将提高查询的效率. 在子查询中,NOT IN子句将执行一个内部的排序和合 并. 无论在哪种情况下,NOT IN都是最低效的 (因为它对子查询中的表执行了一个全表遍历). 为了避 免使用NOT IN ,我们可以把它改写成外连接(Outer Joins)或NOT EXISTS. 
    -----这样试下呢上面看错了。。以为是别的写法。。呵呵见笑了。。
    1>:
    select * from A where exists (select 1 from B where exists (select 1 from C where c.id = b.id) and a.id=b.id)
    2>:
    select * from A where exists (select 1 from B where not exists (select 1 from C where c.id = b.id) and a.id=b.id)
      

  3.   

    1、查出A表的所有信息:条件id同时存在于B、C表2、查出A表的所有信息:条件id存在于B但是不存在于 C表
    抛开上面我说的那个方法,有没有比用exsit、not exsit更好的方法?
      

  4.   

    没有别的了吧,你的索引也有了,用上exists,not exists感觉就可以了。。
      

  5.   

    不知道这两条语句的使用场景
    只是,从语句的逻辑角度,是否可以考虑一下,将这两条语句合并为一个可在直接查出A、B关联(内联)、再与C的关联(左联),这样的话,一个SQL语句就可以了
      

  6.   

    oraclefans说的对,in用exists代替,这个说实话效率上不是很明显,但是not in用not exists代替,那效率上不是一个档次的。亲自试一下就什么都明白了
      

  7.   

    请问下,用连接的效率会比用exsit、not exsit的效率高吗?
      

  8.   


    --1、查出A表的所有信息:条件id同时存在于B、C表select * from A 
    where exists(select null from 
                          (select id from B 
                                     where exists(select null from C 
                                                  where C.id =B.id)) t
                where t.id=A.id)
    --2、查出A表的所有信息:条件id存在于B但是不存在于C表
    select * from A 
    where exists(select null from 
                          (select id from B 
                                     where not exists(select null from C 
                                                  where C.id =B.id)) t
                where t.id=A.id)
      

  9.   


    select A.* from A,B,C where a.id = b.id and b.id = c.id; select * from A 
    where exists(select null from 
                          (select id from B 
                                     where exists(select null from C 
                                                  where C.id =B.id)) t
                where t.id=A.id)
    --上面的两种,那种效率高?
    用exists还是内连接??