题解 | #获取员工其当前的薪水比其manager高#
获取员工其当前的薪水比其manager当前薪水还高的相关信息
https://www.nowcoder.com/practice/f858d74a030e48da8e0f69e21be63bef
select emp.emp_no, dep.emp_no, s.salary as empsala, (select salary from salaries s2 where dep.emp_no = s2.emp_no) as mgrsala from dept_emp emp inner join dept_manager dep on emp.dept_no = dep.dept_no inner join salaries s on emp.emp_no = s.emp_no where (emp.emp_no not in (select emp_no from dept_manager)) having empsala > mgrsala -- 1 得到一个表,里面有员工和他的领导的员工号,员工的工资和他领导的工资 -- 至于领导的工资可以用子查询查出来
在SQL中,你不能在WHERE
子句中直接使用SELECT
列表中定义的别名(如empsala
和mgrsala
)。这是因为WHERE
子句在执行顺序中先于SELECT
列表进行处理,所以在WHERE
子句中,SQL引擎还不知道empsala
和mgrsala
这两个别名代表什么。
你可以通过以下几种方式之一来解决这个问题:
- 使用子查询:将整个查询作为一个子查询,然后在外部查询中使用别名进行比较。
- 使用HAVING子句:如果你只是想对聚合结果进行过滤,可以使用HAVING子句(但这在你的情况下不适用,因为你没有使用聚合函数)。