SQL中EXISTS与IN的区别

  1. 网上查了很多关于这两个单词的用法,说法很多,但大同小异,现在归纳如下:   
  2.   
  3. 关于EXISTS与IN的区别:  
  4. EXISTS检查是否有结果,判断是否有记录,返回的是一个布尔型(TRUE/FALSE)。  
  5. IN是对结果值进行比较,判断一个字段是否存在于几个值的范围中,所以 EXISTS 比 IN 快。  
  6.   
  7.   
  8. 主要区别是:  
  9. exists主要用于片面的,有满足一个条件的即可,  
  10. in主要用于具体的集合操作,有多少满足条件.   
  11.   
  12. exists是判断是否存在这样的记录,  
  13. in是判断某个字段是否在指定的某个范围内。  
  14. exists快一些吧 。  
  15.   
  16. in适合内外表都很大的情况,exists适合外表结果集很小的情况。  
  17.   
  18.   
  19. 在ASKTOM的讲解:  
  20. Well, the two are processed very very differently.  
  21.   
  22. Select * from T1 where x in ( select y from T2 )  
  23.   
  24. is typically processed as:  
  25.   
  26. select *   
  27. from t1, ( select distinct y from t2 ) t2  
  28. where t1.x = t2.y;  
  29.   
  30. The subquery is evaluated, distinct'ed, indexed (or hashed or sorted) and then   
  31. joined to the original table -- typically.  
  32.   
  33.   
  34. As opposed to   
  35.   
  36. select * from t1 where exists ( select null from t2 where y = x )  
  37.   
  38. That is processed more like:  
  39.   
  40.   
  41. for x in ( select * from t1 )  
  42. loop  
  43. if ( exists ( select null from t2 where y = x.x )  
  44. then   
  45. OUTPUT THE RECORD  
  46. end if  
  47. end loop  
  48.   
  49. It always results in a full scan of T1 whereas the first query can make use of   
  50. an index on T1(x).  
  51.   
  52.   
  53. So, when is where exists appropriate and in appropriate?  
  54.   
  55. Lets say the result of the subquery  
  56. select y from T2 )  
  57.   
  58. is "huge" and takes a long time. But the table T1 is relatively small and   
  59. executing ( select null from t2 where y = x.x ) is very very fast (nice index on   
  60. t2(y)). Then the exists will be faster as the time to full scan T1 and do the   
  61. index probe into T2 could be less then the time to simply full scan T2 to build   
  62. the subquery we need to distinct on.  
  63.   
  64.   
  65. Lets say the result of the subquery is small -- then IN is typicaly more   
  66. appropriate.  
  67.   
  68.   
  69. If both the subquery and the outer table are huge -- either might work as well   
  70. as the other -- depends on the indexes and othe* **ctors.   


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值