(十五)MySQL语法-子查询(三)
四:放在exisit后面的select 查询语句(称为相关子查询) select EXISTS(select employee_id from employees);--结果:1 select EXISTS(select employee_id from employees where salary='过家家');--结果:0 由此可见exists返回的是Boolean类型的值,其中1:有 0:没有 案例1:查询有员工的部门名 select d.department_name from departments d where EXISTS( select * from employees e where e.department_id=d.department_id ); 案例2;查询没有女朋友的男神信息 #使用in的方式进行查询 use girls select * from boys bo where bo.id not in( select b.boyfriend_id from beauty b--注意:后面不能再加where,关联条件了 ) ; #使用exists 子查询 select * from boys bo where not EXISTS( select * from beauty b where b.boyfriend_id=bo.id--注意:EXISTS后面必须得加连接条件 ) ; 练习题案例 查询各部门中工资比本部门平均工资高的员工的员工号、姓名、工资 首先,查询本部门的平均工资 select avg(salary),department_id from employees GROUP BY department_id; 最后,连接刚刚查询出来的结果集,和employees表,进行筛选 select e.employee_id,e.salary,e.last_name,e.department_id from employees e INNER JOIN ( select avg(salary) ag,department_id dd from employees GROUP BY department_id ) avg on avg.dd=e.department_id where e.salary>avg.ag; 案例:查询管理者是king的员工姓名和工资 首先;查询姓名为king的员工编号 select employee_id from employees where last_name='king'; 最后查询哪个员工的manager_id=刚刚查询出来的employee_id select last_name,salary from employees where manager_id in( select employee_id from employees where last_name='king' );