相关子查询外部查询的多个结果

时间:2020-05-18 12:50:06

标签: mysql sql subquery correlated-subquery

我想知道内部查询是否可以返回多个结果,然后由外部查询查询?

以下是可重现的示例:

在此示例中,我想知道每个部门的最高薪员工的姓名和工资。

CREATE TABLE Worker (
    WORKER_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    FIRST_NAME CHAR(25),
    LAST_NAME CHAR(25),
    SALARY INT(15),
    JOINING_DATE DATETIME,
    DEPARTMENT CHAR(25)
);

INSERT INTO Worker 
    (WORKER_ID, FIRST_NAME, LAST_NAME, SALARY, JOINING_DATE, DEPARTMENT) VALUES
        (001, 'Monika', 'Arora', 100000, '14-02-20 09.00.00', 'HR'),
        (002, 'Niharika', 'Verma', 80000, '14-06-11 09.00.00', 'Admin'),
        (003, 'Vishal', 'Singhal', 300000, '14-02-20 09.00.00', 'HR'),
        (004, 'Amitabh', 'Singh', 500000, '14-02-20 09.00.00', 'Admin'),
        (005, 'Vivek', 'Bhati', 500000, '14-06-11 09.00.00', 'Admin'),
        (006, 'Vipul', 'Diwan', 200000, '14-06-11 09.00.00', 'Account'),
        (007, 'Satish', 'Kumar', 75000, '14-01-20 09.00.00', 'Account'),
        (008, 'Geetika', 'Chauhan', 90000, '14-04-11 09.00.00', 'Admin');


找到每个部门的最高薪水很容易:

SELECT MAX(SALARY), DEPARTMENT
FROM Worker
GROUP BY DEPARTMENT;

但是我还要如何将获得这些薪水的雇员的姓名添加到结果中?

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以对运算符IN使用查询:

SELECT * FROM Worker
WHERE (DEPARTMENT, SALARY) IN (
  SELECT DEPARTMENT, MAX(SALARY) 
  FROM Worker
  GROUP BY DEPARTMENT 
);

或者如果您将MySql 8.0+与RANK()窗口函数一起使用:

SELECT w.* 
FROM (
  SELECT *, RANK() OVER (PARTITION BY DEPARTMENT ORDER BY SALARY DESC) rnk
  FROM Worker
) w
WHERE w.rnk = 1

请参见demo
结果:

> WORKER_ID | FIRST_NAME | LAST_NAME | SALARY | JOINING_DATE        | DEPARTMENT
> --------: | :--------- | :-------- | -----: | :------------------ | :---------
>         3 | Vishal     | Singhal   | 300000 | 2014-02-20 09:00:00 | HR        
>         4 | Amitabh    | Singh     | 500000 | 2014-02-20 09:00:00 | Admin     
>         5 | Vivek      | Bhati     | 500000 | 2014-06-11 09:00:00 | Admin     
>         6 | Vipul      | Diwan     | 200000 | 2014-06-11 09:00:00 | Account