select count(distinct(f_service_id)) from wb_cust_contact_t
     where f_contact_result = 1
     and f_stat_time>=to_date('2011-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss') 
     and f_stat_time<=sysdate
     and f_event = '14'
     and f_service_kind not in('11','8','10')怎么用not exists 代替not in

解决方案 »

  1.   

    不用not exists.and f_service_kind not in('11','8','10')
    -->
    and f_service_kind <>'11' and f_service_kind <> '8' and f_service_kind <> '10'
      

  2.   

    -- 这里的 not in 里面写的是具体的数值,没有关联另外的表,所以:没有必要用not exists替换!
    -- 你实在喜欢倒腾的话,就这样写啦:
    with a as (select '11' as f_service_kind from dual
                                union all select '8' as f_service_kind from dual
                                union all select '10' as f_service_kind from dual )
    select count(distinct(f_service_id)) from wb_cust_contact_t
      where f_contact_result = 1
      and f_stat_time>=to_date('2011-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss') 
      and f_stat_time<=sysdate
      and f_event = '14'
      and not exists (select 1 from a where a.f_service_kind=wb_cust_contact_t.f_service_kind);
      

  3.   

    这个sql效率有多低阿?楼主用大量数据测试了吗?花了多少时间
    感觉没有太大需要改动的,楼主可以把where条件的顺序调下,
    固定值和能去除大量数据的条件放到最后面,把需要作运算的条件往前放!
      

  4.   

    ---不用not exists not in效率会更高写,具体看一下执行的计划
    select count(distinct(f_service_id)) from wb_cust_contact_t
      where f_contact_result = 1
      and f_stat_time>=to_date('2011-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')  
      and f_stat_time<=sysdate
      and f_event = '14'
      and  f_service_kind <>'11' and f_service_kind <> '8' and f_service_kind <> '10'
      

  5.   

    这个SQL的效率提升点主要是f_contact_result和f_event,看上去都不是主键,想要提高效率可以给这两个字段添加索引(前提是没有的话),然后前置,如下:
    select count(distinct(f_service_id)) from wb_cust_contact_t
      where f_contact_result = 1
      and f_event = '14'
      and f_stat_time>=to_date('2011-01-01 00:00:00','yyyy-mm-dd hh24:mi:ss')  
      and f_stat_time<=sysdate
      and f_service_kind not in('11','8','10');
    另,where后的第一个字段一定要是有索引的;in和exists在这里没法替换,而且就算能替换,也不一定能替换效率,in和EXISTS的效率要看实际的数据量,是相对的,不是绝对的。希望对你有帮助……
      

  6.   

    添加一个f_contact_result、 f_event、f_stat_time复合索引,速度应该会快好多
      

  7.   

    建立索引 not in 用<>代替 注意联合索引的建立 where 后面的查询条件第一个必须是建立索引的!!
     
      

  8.   

    是固定的就用not in,是在表中的就使用not exitss