SQL

子查询

exists 和 not exists 关键字的用法

范例:查询出有员工的部门有哪些

  • 示例图:
    oracle(21)_SQL_exists 和 not exists 关键字的用法
    oracle(21)_SQL_exists 和 not exists 关键字的用法

● exists 关键字的用法

  • exists (sql 返回结果集为真)
  • 示例图:
    oracle(21)_SQL_exists 和 not exists 关键字的用法

范例:

● not exists 关键字的用法

  • not exists (sql 不返回结果集为真)
  • 示例图:
    oracle(21)_SQL_exists 和 not exists 关键字的用法

以上操作完整源码:

--查询出有员工的部门有哪些
--in关键字尽量要少使用,因为性能比较低,可以使用 exists 来代替性能很高
select * from dept t where t.deptno in (select distinct deptno from emp);

--exists()子查询的记录数是 0 则整个表达式是 false 如果大于 0 为 true,
--exists 子查询一般是要和外侧查询关联的
select * from emp t where exists (select * from dept d where d.deptno = 50);

--用exists来实现查询出有员工的部门有哪些
select * from dept t where exists (select * from emp e where e.deptno = t.deptno);

--用not exists来实现查询出没有员工的部门有哪些
select * from dept t where not exists (select * from emp e where e.deptno = t.deptno);

如有错误,欢迎指正!

相关文章:

  • 2021-05-20
  • 2021-10-18
  • 2021-07-21
  • 2021-12-12
  • 2021-11-18
  • 2021-05-14
  • 2021-11-09
  • 2021-08-29
猜你喜欢
  • 2022-01-10
  • 2022-01-21
  • 2021-11-23
  • 2022-02-05
  • 2021-12-22
  • 2021-11-10
  • 2021-11-05
相关资源
相似解决方案