MySql教程

MySQL-子查询

本文主要是介绍MySQL-子查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

子查询

单行子查询

--主查询
select employee _id, last_name.salary
from employees
where salary >(
    select salary
    from employees
    where last_name='abel'
);

多行子查询

  • any:满足值列表中,任意一个条件即可
  • OR 满足所有值列表中的任意一个。
  • in :等于值列表中任意一个
-- 题目:返回其它部门中,比job_id为‘IT_PROG’部门 任一工资低的员工的 员工号、姓名、job_id以及salary
select employee_id , last_name, job_id,salary
from employees
where salary <any (
    select salary 
    from employees 
    where job_id='IT_PROG'
) AND job_id !='IT_PROG';

相关子查询

-- 问题:查询员工中工资大于本部门平均工资的员工的last_name, salary 和其department_id及平均工资

select last_name, salary, department_id, (select avg(salary) from employees where department_id=e1.department_id)
from employees e1
where salary >(
    select avg(salary)
    from employees e2
    where e2.departent_id= e1.department_id
)
-- 解法二
select last_name, salary, e1.department_id,e2.avg_sal
from employees e1, (
    select avg(salary) avg_sal, department_id
    from employees 
    group by departent_id
)e2
where e1.departent_id =e2.department_id
and e1.salary>e2.avg_sal;

其它子查询

--问题:查询与141号或者174号员工的manager_id和department_id相同的其他员工的employee_id, manager_id ,department_id 
select employee_id, manager_id, department_id
from employees
where manager_id in (
    select manager_id 
    from employees
    where employee_id in (141,174)
) and department_id in (
    delect department_id 
    form employees 
    where employee_id in (141, 174)
);
这篇关于MySQL-子查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!