菜鸟问题:结果有问题,sql,join,where,“<”运算符

Newbie question: Problem with results, sql, join, where, "<" operator

任务:

Show the last names of employees, employees salary, and their managers last names and salary. We are only interested in those employees who were hired before their managers and have salary below the average of their departments.

代码:

select e.last_name, e.salary, e.hire_date, e.department_id,
       m.last_name, m.salary, m.hire_date 
from employees e  
join employees m  on (e.manager_id=m.employee_id) 
 where e.salary <(select avg(e.salary) 
                  from employees e  
                  where e.department_id=e.department_id) 
and e.hire_date < m.hire_date

问题:

我对结果有疑问。其中我得到了

然而,当我将e.salary < (select avg(e.salary)...之间的<运算符改为相反的>时(假设这次我们感兴趣的是那些薪水高于部门平均水平的人),结果是正确的。

我不明白为什么会这样?我试图通过添加这一行

来解决这个问题
 and e.salary<>(select avg(e.salary) 
               from employees e 
               where e.department_id=e.department_id)`

但它不起作用。任何人都可以帮助我了解正在发生的事情或只是指明方向吗?

这是我的table:

这是一个微妙的问题。在您的子查询中,您使用的别名 employees e 与您在主查询中使用的别名相同。这意味着子查询 e.department_id=e.department_id 中的过滤器实际上并没有按照您的想法进行:由于命名空间范围,它实际上折叠为 1=1。因此,您得不到预期的结果,因为子查询不相关。

解决方案很简单:在子查询中使用不同的别名,如下所示:

select e.last_name, e.salary, e.hire_date, e.department_id,
       m.last_name, m.salary, m.hire_date 
from employees e  
join employees m  on (e.manager_id=m.employee_id) 
 where e.salary <(select avg(e2.salary) 
                  from employees e2  
                  where e.department_id=e2.department_id) 
and e.hire_date < m.hire_date
;