好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

SQL查询中in和exists的区别分析

select * from A where id in (select id from B);

select * from A where exists (select 1 from B where A.id=B.id);

对于以上两种情况,in是在内存里遍历比较,而exists需要查询数据库,所以当B表数据量较大时,exists效率优于in。

1、select * from A where id in (select id from B);

in()只执行一次,它查出B表中的所有id字段并缓存起来。之后,检查A表的id是否与B表中的id相等,如果相等则将A表的记录加入结果集中,直到遍历完A表的所有记录。
它的查询过程类似于以下过程:

代码如下:

查看更多关于SQL查询中in和exists的区别分析的详细内容...

  阅读:40次