我在竞赛中遇到了这个SQL查询。
表格:员工
+------+------+--------+--------+
| ID | Name | Salary | Branch |
+------+------+--------+--------+
| 1 | e1 | 10000 | cse |
| 2 | e2 | 20000 | ece |
| 3 | e3 | 12000 | ece |
| 4 | e4 | 25000 | eee |
| 5 | e5 | 15000 | ece |
+------+------+--------+--------+
查询:
select * from Employees as e1 where e1.Branch="ece" and (select count(*) from Employees as e2 where e2.Branch="ece" and e1.Salary > e2.Salary) >= 2;
我得到的输出是:
+------+------+--------+--------+
| ID | Name | Salary | Branch |
+------+------+--------+--------+
| 2 | e2 | 20000 | ece |
+------+------+--------+--------+
我不明白为什么得到这个输出。我可以猜测,可能是给予了最高员工和最高工资 分支机构 ece 。对查询进行一些解释会有所帮助。
答案 0 :(得分:1)
这是 Correlated Subquery
的示例,其中内部查询和外部查询同时执行
select * from Employees as e1
where e1.Branch="ece" and
(
select count(*) from Employees as e2 where
e2.Branch="ece" and e1.Salary > e2.Salary
) >= 2;`
对于外部查询的每一行,都会在内部查询中进行比较,并使用内部查询的结果从外部查询中获取最终结果。