查询曾经在所有部门【departments】都工作过的雇员【employees】的雇员编号和姓名

题目解读:

此题涉及到的数据库表:【departments -- 部门信息】、【dept_emp -- 部门_员工 关系表】、【employees -- 员工信息】

方法一:not exists

  1. 思路
    查找符合下列条件的雇员:不存在一个部门,雇员没有在该部门工作过;
  2. sql 语句
    select emp_no, -- 方法1
    first_name,
    last_name
    from employees
    where not exists( -- 不存在这样的部门
    select *
    from departments
    where not exists( -- 员工没有工作过
    select *
    from dept_emp
    where departments.dept_no=dept_emp.dept_no and
    dept_emp.emp_no=employees.emp_no));
    方法二:简单的逻辑
  3. 思路
    查找符合下列条件的雇员:雇员工作过的部门数 == 所有的部门数
  4. sql 语句
    select employees.emp_no, -- 方法2
    first_name,
    last_name
    from employees,
    dept_emp
    where employees.emp_no=dept_emp.emp_no
    group by emp_no
    having count() = (
    select count(
    )
    from departments);

猜你喜欢

转载自www.cnblogs.com/ggyzzz/p/12291768.html
今日推荐