SQL查询中in、exists、not in、not exists的用法与区别
1、in和exists in是把外表和内表作hash(字典集合)连接,而exists是对外表作循环,每次循环再对内表进行查询。一直以来认为exists比in效率高的说法是不准确的,如果查询的两个表大小相当,那么用in和exists差别不大;如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in。 例如:表A(小表),表B(大表) 方式一:索引使用 1)select * from A where id in(select id from B) -->效率低,用到了A表上id列的索引 2)select * from A where exists(select id from B where id=A.id) -->效率高,用到了B表上id列的索引 3)select * from B where id in(select id from A) -->效率高,用到了B表上id列的索引 4)select * from B where exists(select id from A where id=B.id) -->效率低,用到了A表上id列的索引 方式二:遍历使用 1)in()只执行一次,它查出B表中的所有id字段并缓存起来。然后检查A表的id是否与B表中的id相等,如果相等则将A表的记录加入结果集中,直到遍历完A表的所有记录。