exists 和not exists用法

exists 和not exists用法

exists表示()内子查询语句返回结果不为空说明where条件成立就会执行主sql语句,如果为空就表示where条件不成立,sql语句就不会执行。

not exists和exists相反,子查询语句结果为空,则表示where条件成立,执行sql语句。

dept,emp表中关联字段deptno,部门dept表有deptno为10,20,30,40 的部门id号,emp员工表中有员工信息及所在的部门deptno号,分别有属于10,20,30,40的部门ID号员工,共有14位员工。

案例一、

  select * from emp e where  exists (select 1 from dept t where t.deptno=10);

  结果查询出所有员工信息14条记录,exits子查询中结果不为空,就会执行主sql语句,所以查询出emp所有记录。

案例二、
    select * from emp e where  exists (select 1 from dept t where t.deptno=10 and t.deptno=e.deptno);
结果查询出属于部门ip 10的所有员工信息,如果emp表中员工有属于20,30,40部门的通过exists子查询是为空的记录,主sql不查询。属于部门10的员工有记录,主sql执行。

案例三、
    select * from emp e where  not exists (select 1 from dept t where t.deptno=10);

结果记录为空,因为not exists子查询结果有值,不为空,则主sql不查询。

案例四、
   select * from emp e where not exists (select 1 from dept t where t.deptno=10 and t.deptno=e.deptno);
结果查询出属于部门id不属于10的所有员工信息,emp表中员工有属于10部门的通过not exists子查询是不为空的记录,主sql不查询。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22526482/viewspace-2122610/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/22526482/viewspace-2122610/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值