zoukankan      html  css  js  c++  java
  • not in 和not exists

    not in 逻辑上不完全等同于not exists,如果你误用了not in,小心你的程序存在致命的BUG,请看下面的例子:

    正如所看到的,not in出现了不期望的结果集,存在逻辑错误。如果看一下上述两个select 语句的执行计划,也会不同,后者使用了hash_aj,所以,请尽量不要使用not in(它会调用子查询),而尽量使用not exists(它会调用关联子查询)。如果子查询中返回的任意一条记录含有空值,则查询将不返回任何记录。如果子查询字段有非空限制,这时可以使用not in,并且可以通过提示让它用hasg_aj或merge_aj连接。

    如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而not exists的子查询依然能用到表上的索引。所以无论哪个表大,用not exists都比not in 要快。

    备注:

    在not exists(select。。。。or)是不对的

     1 select *
     2   from bgymdm_magorg mdm, bgy_morg@csmdp mdp
     3  where mdm.departmentid = mdp.organizationid
     4    and not exists (
     5         
     6         select t.*
     7           from (select mdm.*,
     8                         (select org.pk_fatherorg
     9                            from org_orgs org
    10                           where org.pk_org = mdm.parentorg) uapfatherorg
    11                    from bgymdm_magorg mdm) t
    12          where mdm.code = mdp.code
    13             or mdm.name = mdp.name
    14             or t.uapfatherorg = mdp.fatherorgnization
    15         
    16         )

    在not exists(select。。。。and)是对的

     1 select *
     2   from bgymdm_magorg mdm, bgy_morg@csmdp mdp
     3  where mdm.departmentid = mdp.organizationid
     4    and not exists (
     5         
     6         select t.*
     7           from (select mdm.*,
     8                         (select org.pk_fatherorg
     9                            from org_orgs org
    10                           where org.pk_org = mdm.parentorg) uapfatherorg
    11                    from bgymdm_magorg mdm) t
    12          where mdm.code = mdp.code
    13             and mdm.name = mdp.name
    14             and t.uapfatherorg = mdp.fatherorgnization
    15         
    16         )
    ---- 动动手指关注我!或许下次你又能在我这里找到你需要的答案!ZZZZW与你一起学习,一起进步!
  • 相关阅读:
    zabbix_agent 主动模式配置
    zabbix 监控ipmi
    超级详细全截图化VMware 安装ubantu
    docker 部署
    C# DataTable和List转换操作类
    C#类型转换工具类
    C# 注册windows 服务
    C# wsdl.exe 生成类文件
    visual studio code download url
    c# xml序列化和反序列化
  • 原文地址:https://www.cnblogs.com/zzzzw/p/4971526.html
Copyright © 2011-2022 走看看