我有作业问题,很抱歉,我对此很不满意。
我有一个Employee表。我想查询以查找其部门中薪水最高的员工的姓名
我写过:
Select emp_name
from employee
where salary=any(select max(salary) from employee group by dept_no)
表名:员工
emp_name salary Dept_no
e1 1000 10
e2 2000 10
e3 2000 20
e4 3000 20
输出应为:
e2
e4
但是这是错误的,因为有人可以告诉我为什么吗?
您的代码缺少部门的链接,仅设置了工资条件。您必须将子查询加入到表中:
Select e.emp_name
from employee e inner join(
select dept_no, max(salary) salary
from employee
group by dept_no
) t on t.dept_no = e.dept_no and t.salary = e.salary
或不存在:
Select e.emp_name
from employee e
where not exists(
select 1 from employee
where dept_no = e.dept_no and salary > e.salary
)
您的问题是部门之间没有联系。因此,部门B中的某人可能会获得部门A中某人的最高薪水,但可能不是该部门中收入最高的人。
对于这种方法,我建议在子查询中使用correlation子句,而不是GROUP BY
:
select e.emp_name
from employee e
where e.salary = (select max(e2.salary)
from employee e2
where e2.dept_no = e.dept_no
------------------------^ correlation clause
);
注意表别名和限定列名的使用。您应该在编写查询时always限定所有表引用-确保查询符合您的意图,并使查询对其他人更易于理解。
如果性能有问题,请使用employee(dept_no, salary)
。