in or exits

1 in 和 exits存在的原因

   不是所有的查询都有关联

2 in 和 exits并存的原因

   in 和 exits 有各自的优势

3 in 和 exits的原理

   in  先执行子查询 然后执行主表查询,exits先执行主表查询,后执行子查询过滤

4 何时使用in

   过滤性不强,主表不是大表

   例:

select * from dep d where d.parent_id in (  select s.dep_id from student  s where s.stu_name like '%小明%'
)
 

5 何时使用exits

   过滤性很强,主表可以是大表(主要靠过滤)
  例:

select * from dep d where d .id = 101 and exits (select 1 from student s where s.stu_name like '%小明%')
 

6 in 和 exits 对比

   适合用in的 查询相关分类

       select * from category c where c.parent_id in(select i.category_id from info i where info.name like '%中国%' ) 

       要比exits有优势

   适合用exits的某时间段的相关分类

     select * from category  createDate< to_date('2012-09-29 10:00:00','yyyy-mm-dd hh24:mi:ss')

and createDate< to_date('2012-10-01 00:00:00','yyyy-mm-dd hh24:mi:ss')

and exits (select i.category_id from info i where info.name like '%中国%' )  

      要比in有优势

7 总结in与exits

   如果主表是大表 不首先考虑exits,但是如果过滤性很强要考虑exits.

   如果主表是小表,两种差不了多远。因为有时候exits的优势是在过滤上 如果主表本来数据很少过滤的影响不大。

猜你喜欢

转载自maclab.iteye.com/blog/1694229