请教in 和 exists 是使用列子一直搞不懂他们的区别

解决方案 »

  1.   

    in函数表示某一字段值是否在in的列表值范围内
    如:select *  from tb where type in('A','F','O'...)
    exists表示某个表是否存在记录?
    如:
    if exists(select 1 from tb where salary>10000 and type='A')
    print '存在'
    else
    print '不存在'exists的速度比in 快
      

  2.   

    使用 EXISTS 关键字引入一个子查询时,就相当于进行一次存在测试。外部查询的 WHERE 子句测试子查询返回的行是否存在。子查询实际上不产生任何数据,它只返回 TRUE 或 FALSE 值。In 确定给定的值是否与子查询或列表中的值匹配。Select * from t1 where x in ( select y from t2 )
    相当于
    select * 
      from t1, ( select distinct y from t2 ) t2
     where t1.x = t2.y;如果t2的记录很多而t1的记录相对较少的话,建议采用Exists;相反,如果t1的记录很多而t2的记录相对较少,则建议采用In写法。
      

  3.   

    楼上的,if exists这种写法是在sql server里的吧in,exists各有各的用处,速度不一定的,要看数据。select * from emp where deptno in (select deptno from dept);select * from emp where exists(select 1 from deptno where deptno = emp.deptno);
      

  4.   

    in:使用在字段值与字段名间;
    exists:使用在字段名与表(视图)间。
      

  5.   

    in 和exsits表达的意思是一样的,
    但是一般建议使用exsitsselect * from A where id in(1,2,3);  --id在可选范围中去取值.select * from A where id in(select id from B);-- 选出A表与B表中id相等的数据,等价于select A.* from A,B where A.id=B.idselect * from A where exists(select 1 from B where B.id = A.id); --表达的意思与上面一条语句相同--当两个表以2个字段以上进行比较时,用exists进行表达则比用in表达方便,如下面一条语句:
    select * from A where exists(select 1 from B where B.id = A.id and B.pno = A.pno); 
      

  6.   

    强烈建议用exsits 效率高,再有就是建议适用表别名,都是提高效率的写sql的规范
    例子:
    select ID from T_table T where T.ID in(A,B,D,C) 
    select ID from T_table T where T.ID exsits(A,B,D,C)