问题描述
我认为以下SQL语句返回的列表薪水少于5000。 但是我的薪水大于或等于5000。我真的不知道为什么。我错过了什么吗?
select salary
from employees
where exists (select 1 from employees e where salary < 5000);
解决方法
查询中exists
运算符内的查询至少返回一行,因此该运算符的计算结果为true
。这里的问题是它与外部查询没有任何关联,因此它为外部查询中的每一行返回相同的结果(即始终为true
)。
要获得所需的结果,您需要通过在内部查询的where
子句中使用来自外部查询的术语来使查询之间相互关联:
SELECT salary
FROM employees e1
WHERE EXISTS (SELECT 1
FROM employees e2
WHERE e1.emp_id = e2.emp_id AND salary < 5000);
但是,说实话,您实际上不需要这里的exists
运算符,并且可以直接查询薪水:
SELECT salary
FROM employees
WHERE salary < 5000