[英]Get field from MYSQL subquery from outer main query
In my mysql db I have an employee table ( EMP
) and a department table ( DEPT
) and want to find employees with highest salary in each department .在我的 mysql 数据库中,我有一个员工表 (
EMP
) 和一个部门表 ( DEPT
),并希望找到每个部门中薪水最高的员工。
So first I grouped the departments like this所以首先我像这样对部门进行分组
SELECT
dept.DNAME as department,
MAX(emp.SAL) as maximum_sal
FROM
`EMP` emp
JOIN `DEPT` dept ON emp.DEPTNO = dept.DEPTNO
GROUP BY
dept.DNAME
ORDER BY
maximum_sal DESC;
Now to get the employees associated with these departments I have tried doing this:现在为了让与这些部门相关联的员工,我尝试这样做:
SELECT
emp.ENAME,
emp.SAL,
department
FROM
`EMP` emp
WHERE
(department, maximum_sal) IN (
SELECT
dept.DNAME as department,
MAX(emp.SAL) as maximum_sal
FROM
`EMP` emp
JOIN `DEPT` dept ON emp.DEPTNO = dept.DEPTNO
GROUP BY
dept.DNAME
ORDER BY
maximum_sal DESC
);
But I get the error Unknown column 'department' in 'field list'
但我
Unknown column 'department' in 'field list'
What am I doing wrong?我究竟做错了什么? How do I get fields from the inner subquery to show up in my select outer query.
如何从内部子查询中获取字段以显示在我的选择外部查询中。
No matter the MySQL version you can do this:无论 MySQL 版本如何,您都可以这样做:
SELECT emp.ENAME,
emp.SAL,
dept.dname
FROM `EMP` emp
JOIN `DEPT` dept ON emp.DEPTNO = dept.DEPTNO
JOIN
(
SELECT DEPTNO, max(sal) as msal
FROM emp
GROUP BY DEPTNO
) tmp ON tmp.DEPTNO = emp.DEPTNO
AND tmp.msal = emp.sal
GROUP BY dept.DNAME
Your query won't work since your "subquery" is only part of an IN clause which you cannot reference from outside.您的查询将不起作用,因为您的“子查询”只是您无法从外部引用的 IN 子句的一部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.