zoukankan      html  css  js  c++  java
  • [SQL使用经验]选用 IN 还是 EXISTS,哪个性能更好

    一、EXISTS 并非总比IN 快,究竟应该选用 IN 还是 EXISTS ,可参考以下分析:
    1、Select * from t1 where x in ( select y from t2 )
    相当于
    select *
      from t1, ( select distinct y from t2 ) t2
     where t1.x = t2.y;

    2、select * from t1 where exists ( select null from t2 where y = x )
    相当于
       for x in ( select * from t1 )
       loop
          if ( exists ( select null from t2 where y = x.x )
          then
             OUTPUT THE RECORD
          end if
       end loop

    如果t2的记录很多而t1的记录相对较少的话,建议采用第二种写法;相反,如果t1的记录很多而t2的记录相对较少,则建议采用第一种写法。
    其它情况,则需要仔细分析再决定是选择IN还是选择EXISTS

    二、NOT IN 并不等价于NOT EXISTS

    例如下面这两个句子,只有在t1.c1不为NULL的时候,两者返回的记录才是相同的,大家在用NOT EXISTS来替换NOT IN 时可能会忽略掉这一点
    select t1.*
      from table1 t1
     where not exists
     (select t2.c1 from table2 t2 where t2.c1 = t1.c1)

    select t1.*
      from table1 t1
     where t1.c1 not in (select t2.c1 from table2 t2)

  • 相关阅读:
    bzoj 3594: [Scoi2014]方伯伯的玉米田
    普通平衡树(指针splay)
    codeforces 475D. CGCDSSQ
    php 购物车功能
    PHP现阶段发现的不足点
    php 多维数据根据某个或多个字段排序
    redis可视化辅助工具
    Redis在window下安装以及配置
    hive数据操作
    hive 表分区操作
  • 原文地址:https://www.cnblogs.com/cxd4321/p/764178.html
Copyright © 2011-2022 走看看