在本教程中,您将学习如何使用sql exists
运算符来测试子查询是否包含任何行。
exists
运算符用于指定子查询以测试行的存在。 以下是exists
运算符的语法:
exists (subquery)
如果子查询包含任何行,则exists
运算符返回true
。 否则它返回false
。
exists
运算符在找到行后立即终止查询处理,因此,可以利用exists
运算符的此功能来提高查询性能。
我们将使用示例数据库中的employees
和dependents
表进行演示。
以下语句查找至少有一个家属的所有员工:
select
employee_id, first_name, last_name
from
employees
where
exists( select
1
from
dependents
where
dependents.employee_id = employees.employee_id);
执行上面查询语句,得到以下结果:
+-------------+------------+-----------+
| employee_id | first_name | last_name |
+-------------+------------+-----------+
| 100 | steven | lee |
| 101 | neena | wong |
| 102 | lex | liang |
| 103 | alexander | lee |
| 104 | bruce | wong |
| 105 | david | liang |
| 106 | valli | chen |
... ...
| 176 | jonathon | yang |
| 200 | jennifer | zhao |
| 201 | michael | zhou |
| 202 | pat | zhou |
| 203 | susan | zhou |
| 204 | hermann | wu |
| 205 | shelley | wu |
| 206 | william | wu |
+-------------+------------+-----------+
30 rows in set
子查询是相关的。 对于employees
表中的每一行,子查询检查dependents
表中是否有对应的行。 如果有匹配行,则子查询返回一个使外部查询包含employees
表中的当前行的子查询。 如果没有相应的行,则子查询不返回导致外部查询不包括结果集中employees
表中的当前行的行。
要取消exists
运算符,可以使用not
运算符,如下所示:
not exists (subquery)
例如,以下查询查找没有任何家属的员工:
select
employee_id, first_name, last_name
from
employees
where
not exists( select
1
from
dependents
where
dependents.employee_id = employees.employee_id);
执行上面查询语句,得到以下结果:
如果子查询返回null
,则exists
运算符仍返回结果集。 这是因为exists
运算符仅检查子查询返回的行的存在。 行是否为null
无关紧要。
在以下示例中,子查询返回null
,但exists
运算符仍然计算为true
:
select
employee_id, first_name, last_name
from
employees
where
exists( select null)
order by first_name , last_name;
该查询返回employees
表中的所有行。
在本教程中,您学习了如何使用sql exists
运算符来测试子查询返回的行的存在。