将不相关的子查询重写为相关的子查询

Rewriting uncorrelated subquery to correlated subquery

我正在使用默认的 oracle scott 数据库和额外的 table 项目,其中有两列:projectnoempno.

我想select每个项目中薪水最高的员工姓名。

我知道如何使用不相关的子查询:

SELECT p.projno, 
       e.sal, 
       e.ename
  FROM emp e 
 INNER 
  JOIN proj_emp p 
    ON e.empno = p.empno
 WHERE (e.sal, p.projno) 
    IN (SELECT MAX(e.sal), 
               p.projno 
          FROM emp e INNER JOIN proj_emp p 
            ON e.empno = p.empno
         GROUP BY p.projno)

但是,我被要求使用写在 WHERE 子句中的相关子查询来完成它,但我想知道这是否可能?

使用window函数:

SELECT projno, sal, ename
FROM (SELECT p.projno, e.sal, e.ename,
             MAX(e.sal) OVER (PARTITION BY p.projno) as max_sal
      FROM emp e INNER JOIN
           proj_emp p 
           ON e.empno = p.empno
     ) ps
WHERE sal = max_sal;

我愿意:

SELECT t.*
FROM (SELECT p.projno, e.sal, e.ename,
             DENSE_RANK() OVER (PARTITION BY p.projno ORDER BY e.sal DESC) AS Seq
      FROM emp e INNER JOIN
           proj_emp p 
           ON e.empno = p.empno
     ) t
WHERE Seq = 1;

编辑 : 如果你想用相关的子查询来做,那么我会重写你的查询使 correlated :

SELECT p.projno, e.sal, e.ename
FROM emp e INNER JOIN 
     proj_emp p 
     ON e.empno = p.empno
WHERE e.sal = (SELECT MAX(e1.sal)
               FROM emp e1 INNER JOIN 
                    proj_emp p1 
                    ON e1.empno = p1.empno
               WHERE p1.projno = p.projno
              );