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/