oracle中exists用法?

如题所述

exists可以说是oracle数据库开发中比较常见的用法,用exists可以提高sql的效率,可以取代in。

    比如   a,b 关联列为 a.id = b.id,现在要取 a 中的数据,其中id在b中也存在:
    select * from a where exists(select 1 from b where a.id = b.id)

    现在要取 a 中的数据,其中id在b中   不存在:
    select * from a where not exists(select 1 from b where a.id = b.id)

用法详解

    exists是判断exits后面的sql语句是否为真,若为真则整个sql句子成立,否则没有任何记录。例子:

    select 1 from dual where exists (select 1 from dual where 2=1);

    上面的情况肯定是没有记录。

    select 1 from dual where exists (select 1 from dual where 1=1);

    上面的情况是有记录返回的。

    判断另外的表中是否包含某个表的外键记录。例子:

    select * from table_test a

    where exists (select 1 from scott.carol_tmp where pps_master=a.pps_master);

    这个sql是要检查table_test中的pps_master是否在carol_tmp中。其实用in也可以实现同样的效果,但是in的话效率要低些,特别是碰上一些大表。用exists和in的性能就体现出来了。

温馨提示:答案为网友推荐,仅供参考
相似回答