sql语句中 [not]exists和[not]in的区别

笔记哥 / 04-18 / 5点赞 / 0评论 / 838阅读
**前言**:近期在处理业务实际问题时发现使用in导致查询速度非常慢,于是查阅资料后发现使用exists能极大缩短查询时间,便将此经历记录下来。 # 数据源: grade表 ![](https://cdn.res.knowhub.vip/c/2504/19/7ae15081.png?G1YAAETn9LwUKCDZvtMdbolTE20GJLIIKiWs13vO2jfR9zcwLD%2bj9tn2h7%2fUPhupcURxAsPZkLwEIOIXh6YSrggVy2s0) stu\_info表 ![](https://cdn.res.knowhub.vip/c/2504/19/970edf79.png?G1cAAETn9LwUKCBx3%2bkOt8SpiWsGLNIIKiWs1%2fP%2f%2b1xE79fBsHzPNlY%2fH37TxuqkxhHFCQxnQwoSgECrKCeppnAPlLxnBw%3d%3d) # exists与in ## in `select name from stu_info where stu_no in ( select distinct stu_no from grade);` 执行结果: ![](https://cdn.res.knowhub.vip/c/2504/19/a352f49b.png?G1YAAMTW3Dgp%2bGBQ22gDdWfqnTUDElkElRLW6%2fn%2ftS%2bi9wswNN%2bj9Rn7w19an0GibHZUAqOyIvligFSYFUluri6nS14jAA%3d%3d) 执行流程: - 首先通过子查询查出有成绩的所有学生学号 - 拿到结果后与user表进行比对 in相当于多个or,如果内表即子查询返回m条记录,那么会用外表去遍历匹配内表,查m次。 in是先查内表,在查外表。 ## exists `select name from stu_info where exists (select * from grade where stu_info.stu_no = grade.stu_no);` 执行结果: ![](https://cdn.res.knowhub.vip/c/2504/19/24468861.png?G1YAAMTW3Dgp%2bGBQ22gDdWfqnTUDElkElRLW6%2fn%2ftS%2bi9wswNN%2bj9Rn7w19an0GibHZUAqOyIvligFSYFUluri6nS14jAA%3d%3d) 执行流程: - 首先查询外表,及执行 select name from stu\_info - 然后根据每条记录执行内表,判断内表中where条件是否成立,成立返回true,该行记录保留;不成立返回false,该行记录舍弃,得到最终结果。 exists是先查外表,再查内表,根据外表行数去逐条查询。 ## 区别: 内表m条,外表n条 in:循环比对n次 exists:循环比对m次 ## 什么时候用in什么时候用exists? - 当内表大外表小,即m>n时,使用in - 当内表小外表大,即m<n时,使用exists - 当内表外表数据量差距很小时,用哪个都可以 # not in 与 not exists: 比对结果与上述相反,但执行流程与上述相同 `select name from stu_info where stu_no not in ( select distinct stu_no from grade);` `select name from stu_info where not exists (select * from grade where stu_info.stu_no = grade.stu_no);` 结果均为: ![](https://cdn.res.knowhub.vip/c/2504/19/7aa42e4a.png?G1cAAMTsdJxIfEK026hD2jvFHc2ARRpBpYT1es9Z%2byb6fgdD4zNan74%2f%2fKb16STKZiUTGJkVISQDVCAlc0hVLlRYsriGAw%3d%3d) # 注: - exists子句中返回结果只为true或false,因此无论select后面时\*或者某些字段效果都一样,mysql在子查询中忽略这些字段。 如`select name from stu_info where exists (select * from grade where stu_info.stu_no = grade.stu_no);`与`select name from stu_info where exists (select 1 from grade where stu_info.stu_no = grade.stu_no);`执行结果是相同的。 - exists子句中返回任意行即为true,即便是包含null值的行,若不返回任何行则为false。 如:`select name from stu_info where exists (select null);`等同于`select name from stu_info;`,因为select null返回含null的行,exists子句返回true。 `select name from stu_info where exists (select * from grade where stu_no = '100');`等同于`select name from stu_info where false;`,不返回任意行,因为exists子查询中的结果不返回任意行,exists返回false。 - 以上可参考文档:Subqueries with EXISTS or NOT EXISTS