EXISTS 函数
说明:EXISTS
用于检查子查询
是否至少返回一行数据。返回值是布尔类型的数据。
EXISTS 与 IN 的区别
说明:
IN
是在括号中子查询的结果,放到一个临时表中,然后遍历临时表去主表中进行查询,也就是临时表驱动主表来进行查询。
EXISTS
是将主表每一行数据,带入到EXISTS
括号中的语句去进行查询判断其是否存在,也就是以主表驱动子查询。
结论:避免循环的次数多,则可以到达性能优化的目的。
- 当主表数据多,子查询的结果集小时,采用
IN
。 - 当主表数据少,子查询到结果集大时,采用
EXISTS
# 例 查询Stu.class_id 在class表中存在的数据
# in 实现
select * from Stu where class_id in (select id from class);
# exists 实现
select * from Stu a where exists (select 1 from class b where a.class_id = b.id );
# 例 查询Stu.class_id 在class表中不存在的数据
# not in 实现
select * from Stu where class_id not in (select id from class);
# not exists 实现
select * from Stu a where not exists (select 1 from class b where a.class_id = b.id );
NOT EXISTS 与 NOT IN
在有索引的情况下,NOT IN
会使索引失效,而NOT EXISTS
依然是可以使用到索引的。在恰当的使用索引时,NOT EXISTS
是比 NOT IN
效率高的