zoukankan      html  css  js  c++  java
  • oracle中in与exists的区别

    exists是用来判断是否存在的,当exists中的查询存在结果时则返回真,否则返回假。not exists则相反。

    exists做为where 条件时,是先对where 前的主查询询进行查询,然后用主查询的结果一个一个的代入exists的查询进行判断,如果为真则输出当前这一条主查询的结果,否则不输出。即exists是对外表作loop循环,每次loop循环再对内表进行查询。而in 是把外表和内表作hash 连接。因此一直以来认为exists比in效率高的说法是不准确的。

    由上分析可以知道如果查询的两个表大小相当,那么用in和exists差别不大;如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:

    现有表A(小表),表B(大表),

    select * from A where col in (select col from B);--效率低

    select * from A where exists(select 1 from B where col =A.col );--效率高

    相反的

    select * from B where col in (select col from A);--效率高

    select * from B where exists(select 1 from A where col =B.col );--效率低

    可以说,以上两个列子,效率高的都是在对B(大表)进行查询的时候,使用的col列的索引。

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

  • 相关阅读:
    python2的比较函数,cmp
    快速排序
    如果a,b,c为自然数,a+b+c=1000,a方+b方=c方,求出abc可能的组合(python实现)
    python之join
    python之functools partial
    Python 3 iter函数用法简述
    python线程之condition
    python 线程 event
    getattr getattribute setattr hasattr delattr
    Properties类
  • 原文地址:https://www.cnblogs.com/longjshz/p/4286823.html
Copyright © 2011-2022 走看看