• in 和 exists性能研究(转)


    原文出处:http://blog.csdn.net/nsj820/article/details/6606732

    in 和exists

    从sql编程角度来说,in直观,exists不直观多一个select;in可以用于各种子查询,而exists好像只适宜于关联子查询。

    in 是把外表和内表作hash join,而exists是对外表作loop,每次loop再对内表进行查询。

    一直以来认为exists比in效率高的说法是不准确的。如果查询的两个表大小相当,那么用in和exists差别不大。

    如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

    例如:表A(小表),表B(大表)

    1:

    select * from A where cc in (select cc fromB)

    效率低,用到了A表上cc列的索引;

    select * from A where exists(select cc fromB where cc=A.cc)

    效率高,用到了B表上cc列的索引。

    相反的

    2:

    select * from B where cc in (select cc fromA)

    效率高,用到了B表上cc列的索引;

    select * from B where exists(select cc fromA where cc=B.cc)

    效率低,用到了A表上cc列的索引。

    带in的关联子查询是多余的,因为in子句和子查询中相关的操作的功能是一样如:

    select staff_name from staff_member wherestaff_id in

     (select staff_id from staff_func wherestaff_member.staff_id=staff_func.staff_id);

    为非关联子查询指定exists子句是不适当的,因为这样会产生笛卡乘积。如:

    select staff_name from staff_member wherestaff_id

    exists (select staff_id from staff_func);

    not in 和notexists

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

    尽量不要使用not in子句。使用minus 子句都比not in 子句快,虽然使用minus子句要进行两次查询:

    select staff_name from staff_member wherestaff_id in (select staff_id from staff_member minus select staff_id from staff_funcwhere func_id like '81%');

    in 与 "=" 的区别

    select name from student where name in('zhang','wang','li','zhao');

    select name from student where name='zhang'or name='li' or name='wang' or name='zhao'

    的结果是相同的。

    总结

    因此,在oracle中有一条比较通用的规则

    1> in适合于外表大而内表小的情况;exists适合于外表小而内表大的情况

    2> 如果两个表相当则in/exists差别不大

    3> 用not exists比not in执行的效率要高的多

    4> 使用in时不对null进行处理

    另外,我们可以这样理解oracle中exists可能会比in的效率会好的原因:

    1> exists检查是否有结果,判断是否有记录,返回的是一个布尔型(TRUE/FALSE),in是对结果值进行比较,判断一个字段是否存在于几个值的范围中。

    2> exists主要用于片面的,有满足一个条件的即可,in主要用于具体的集合操作,有多少满足条件。

    3> exists是判断是否存在这样的记录,in是判断某个字段是否在指定的某个范围内。

  • 相关阅读:
    大数据记录2
    大数据记录1
    Spark 1.5 to 2.1.X
    存储过程定期删除冗余数据
    spark error Caused by: java.io.NotSerializableException: org.apache.hadoop.hdfs.DistributedFileSystem
    spark sql error mismatched input 'union' expecting { <EOF>,''................................
    spark rdd元素println
    spark模型运行时无法连接摸个excutors异常org.apache.spark.shuffle.FetchFailedException: Failed to connect to xxxx/xx.xx.xx.xx:xxxx
    spark模型error java.lang.IllegalArgumentException: Row length is 0
    被简书恶心到了
  • 原文地址:https://www.cnblogs.com/m3Lee/p/3755588.html
Copyright © 2020-2023  润新知