请参阅内部查询Where子句中的外部列

时间:2015-03-05 14:30:39

标签: mysql sql

我有两张表Employee和Departament关系如下所示。对于每个部门,我想获得第五名最佳薪酬员工。

enter image description here

如果我们有MySQL,那么查询应该如何?

我尝试做类似这样的事情,但它没有在内部选择中看到d.id列。

select d.name, e.id from Employee e
join Departament d on d.id = e.dep_id
where e.id = (
    select s.eid from (
        select ee.id as eid, @rowid:=@rowid+1 as rowid from Employee ee, (SELECT @rowid:=0) as init
        where ee.dep_id = d.id
        order by ee.salary desc
     ) s
    where s.rowid = 5
)

是否可以以通用方式执行,而不依赖于任何数据库语义?

如何使用MySQL进行操作以及最佳方法是什么?

2 个答案:

答案 0 :(得分:0)

只需在row_id子句中进行from计算:

select d.name, e.id
from (select ee.*,
             (@rowid := if(@d = dept_id, @rowid + 1,
                           if(@d := dept_id, 1, 1)
                          )
             ) as rowid
      from Employee ee cross join
            (SELECT @rowid := 0, @d := NULL) as init
      order by ee.dept_id, ee.salary desc
     ) e join
     Departament d
     on d.id = e.dept_id
where e.rowid = 5;

而且,是的,有一种ANSI标准方法可以做到这一点。事实上,我可以很容易地想到两种方法。但MySQL不支持窗口函数fetch first 1 row only

答案 1 :(得分:0)

  SELECT X.NAME, X.SALARY AS SAL_5 FROM
     (
     SELECT DEPT.NAME,EMP.SALARY, RANK() OVER (PARTITION BY NAME ORDER BY SALARY DESC) RN
      FROM EMP, DEPT
     WHERE EMP.DEPT_ID=DEPT.DEPT_ID
     ) X
     WHERE X.RN=5;