手把手教MySQL查询:语法、案例、真题 (8. 子查询)"/>
手把手教MySQL查询:语法、案例、真题 (8. 子查询)
8. 子查询
1. 定义嵌套在其他语句中的select语句,称为子查询或内查询外查询:嵌套select语句的外部的查询语句,称为主查询或外查询2. 分类* 按子查询结果集的行列数:标量子查询:一行一列列子查询:一列多行行子查询:一行多列(不常用)* 要求多个判断条件的单行操作符一样* 查询的结果可以被看做一个虚拟的字段表子查询:多行多列3. 特点* 子查询一般放在小括号内* 子查询一般放在条件的右侧* 标量子查询一般搭配着单行操作符使用:> < >= <= = <>* 列子查询一般搭配着多行操作符使用:IN ANY SOME ALLIN/NOT IN:等于列表中的任意一个ANY/SOME:和子查询返回的某一个值比较 >MIN <MAXALL:和子查询返回的所有值比较 >MAX <MIN* 子查询的执行先于主查询,主查询用到了子查询的结果4. 案例-- 查询job_id与141号员工相同、工资比143号员工高的,员工的姓名、工资、job_idselect last_name,salary,job_idfrom employeeswhere job_id = (select job_idfrom employeeswhere employee_id=141) and salary >(select salaryfrom employeeswhere employee_id=143);-- 查询location_id是1400或1700的部门的所有员工的姓名select last_namefrom employeeswhere department_id in (select distinct department_idfrom departmentswhere location_id in (1400,1700));-- 查询其他工种中比工种IT_PROG中任一工资低的员工的员工号,姓名,工种,薪水select employee_id,last_name,job_id,salaryfrom employeeswhere job_id<>'IT_PROG'and salary < any(select diatinct salaryfrom employeeswhere job_id='IT_PROG');-- 查询其他工种中比工种IT_PROG中所有工资低的员工的员工号,姓名,工种,薪水select employee_id,last_name,job_id,salaryfrom employeeswhere job_id<>'IT_PROG'and salary < all(select diatinct salaryfrom employeeswhere job_id='IT_PROG');-- 查询员工编号最小并且工资最高的员工的信息select *from employeeswhere (employee_id,salary)=(select min(employee_id),max(salary)from employees);-- 查询每个部门的员工个数select d.*,(select count(*) from employees ewhere e.department_id=d.department_id)from department d;-- 查询每个部门的平均工资的工资等级select g.grande_level,a.department_id,a.平均工资from job_grades ginner join(select avg(salary) 平均工资,department_idfrom employeesgroup by department_id) aon a.平均工资 between g.lowest_sal and highset_sal;-- 查询没有女朋友的男生信息select bo.*from boys bowhere not exists(select *from beatuy bwhere b.boyfriend_id=bo.id);
更多推荐
手把手教MySQL查询:语法、案例、真题 (8. 子查询)
发布评论