一:用法
正确写法:
select * from A where not exists(select * from B where A.id = B.id);
select * from A where exists(select * from B where A.id = B.id);
错误写法:
select * from areas where id exists(select id from areas where id > 266)
关键是id这块,自己以前老以为是错误写法这种写法。
二:分析过程
1、首先查询select * from table_name的结果
2、将外查询的结果按行代入到子查询,看子查询有没有结果。
3、子查询有结果,exists返回true,not exists返回false;子查询无结果,exists返回false,not exists返回true。
4、返回true则将代入行显示出来,返回false则将带入行隐藏(不显示)。
5、当外查询的结果按行全部代入到子查询中,得到的新的查询结果即该语句的查询结果。
三:exists与in比较
in的用法相信大家很好理解
select * from table_name where col_name [not] in(子查询);
先运行子查询,生成结果集(会放到一个临时标当中)
再运行外查询时,判断col_name在不在子查询里,在的话则返回该行,不在则不返回。
col_name的列数和子查询的列数要相对应
exists的用法相信大家很好理解
将外查询的每一行代入子查询,看子查询返回true还是false。
true则显示,false则不显示。
exists或not exists即是在外查询的结果上,再做一次筛选。
先运行外查询,再运行子查询。
总结:
当外大子小时,即查询的内容很大时,in优于exist【子查询小用in】,减少外查询总的循环次数。
当外小子大时,即查询内容很小时,exists优于in【子查询大用exists】,减少总的循环次数。