MySQL中exists和in的区别

主查询的表称为外表,子查询的表称为内表。
in 是把外表和内表作 hash 连接,而 exists 是对外表作 loop 循环,每次 loop 循环再对内表进行查询。
in查询的子条件返回结果必须只有一个字段,exists就没有这个限制。
内表小,用 in 效率较高;
内表大,用 exists 效率较高;
无论哪个表大,用not exists都比not in要快。因为查询语句使用了not in,那么内外表都进行全表扫描,没有用到索引;而not exists 的子查询依然能用到表上的索引。

posted @ 2023-09-15 20:39  李若盛开  阅读(27)  评论(0)    收藏  举报