题目是这样的:
查询出个人工资高于其所在部门平均工资的员工,列出这些员工的全部个人信息
表employees的结构:
create table employees (
employee_id int primary key, //员工ID
first_name varchar(25),
last_name varchar(25),
salary double, //工资
hired_date date,
department_id int //所在部门ID
)
在看答案前,我自己写的sql语句:
第一种查询方法:
select e1.* from employees e1
where e1.salary>
(
select avg(e2.salary) salary from employees e2
where e1.department_id=e2.department_id
)
第二种查询方法:
select e1.* from employees e1,
(
select department_id, avg(salary) salary from employees
group by department_id
) e2
where e1.department_id=e2.department_id and e1.salary>e2.salary
结果给出的答案简洁好多:
select e1.*
from employees as e1
where e1.salary >
(
select AVG(e2.salary)
from employees as e2
where e1.department_id=e2.department_id
)
看到这个我明白了主查询语句的表别名e1就像成员变量一样可以在子查询中使用,不知道对不对。
但完全想不明白的是,答案的子查询只是用了where子句自连接了两张表的department_id,怎么实现的分组?这是个什么思路或者优化吗?原理是什么?