相关子查询

相关子查询:

即在查询中除了用到子查询外,还用到了表之间的连接(即多表查询)

以下有几个例子:

 1 #18.查询各部门中工资比本部门平均工资高的员工的员工号, 姓名和工资(相关子查询)
 2 select employee_id ,last_name ,salary 
 3 from employees e 
 4 where salary >= (
 5                 select avg(salary)
 6                 from employees e2 
 7                 group by department_id 
 8                 having department_id in (
 9                                         select department_id 
10                                         from employees e3 
11                                         where e.employee_id = e3.employee_id 
12                                         )
13                 );
14             
1 #19.查询每个部门下的部门人数大于 5 的部门名称(相关子查询)
2 select *
3 from departments d 
4 where 5 <= (
5             select count(*)
6             from employees e 
7             where e.department_id = d.department_id 
8             );
1 #20.查询每个国家下的部门个数大于 2 的国家编号(相关子查询)
2 select *
3 from locations l 
4 where 2 < (
5             select count(*)
6             from departments d 
7             where l.location_id = d.location_id 
8             );

 

posted @ 2022-03-23 19:21  jue1e0  阅读(74)  评论(0)    收藏  举报