MySql相关子查询实现

时间:2017-02-26 12:37:01

标签: java sql correlated-subquery

对于以下查询:

SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT Salary) FROM Employee p
           WHERE e.Salary<=p.Salary)

不应该反转子查询中的e.salary<=p.salary条件。我们应该重复比较外部查询中的p.salary列和e.salary列,因此p.salary必须位于左侧。如果我的理解是错误的,请告诉我。

PS:上面的查询试图从Employee表中找到第二高的薪水。

编辑:问题似乎在我的理解中。我在下面提到了我觉得查询可能会执行的方式:

假设我们有一张员工,有4个工资10,20,30,40。现在记录开始逐个处理。所以我们得到以下4个中间实现:

`code`
SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT p.Salary)
           FROM Employee p
           WHERE 10<=p.salary    -- record with salary 10
          );
SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT p.Salary)
           FROM Employee p
           WHERE 20<=p.salary
          );
SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT p.Salary)
           FROM Employee p
           WHERE 30<=p.salary
          );
SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT p.Salary)
           FROM Employee p
           WHERE 40<=p.salary
          );
`code`

这个订单是否正确?不应该是我们试图比较的列,即p.salary必须在左侧,如p.salary>=e.salary

1 个答案:

答案 0 :(得分:1)

这是查询:

SELECT Id, Salary
FROM Employee e
WHERE 2 = (SELECT COUNT(DISTINCT p.Salary)
           FROM Employee p
           WHERE e.Salary <= p.Salary
          );

它计算的不同工资的数量大于或等于任何给定员工的工资。也就是说,查询计算考虑关系的第二大薪水。

如果你“反转”条件,你将会做其他事情。

在大多数数据库中,您可以使用dense_rank()而不是相关的子查询来表达这一点:

SELECT Id, Salary
FROM (SELECT e.*,
             DENSE_RANK() OVER (ORDER BY e.salary) as dr
      FROM Employee e
     ) e
WHERE dr = 2;