MySQL中in、exist的比较

MySQL中in、exist
1、in的原理:
in查询相当于多个or条件的叠加;
in查询就是先将子查询条件的记录全都查出来,假设结果集为B,共有m条记录,然后在将子查询条件的结果集分解成m个,再进行m次查询

2、exist原理:exists对外表用loop逐条查询,每次查询都会查看exists的条件语句,当 exists里的条件语句能够返回记录行时(无论记录行是的多少,只要能返回),
条件就为真,返回当前loop到的这条记录,反之如果exists里的条 件语句不能返回记录行,则当前loop到的这条记录被丢弃,

3、结论:
1)如果查询的两个表大小相当,那么用in和exists差别不大;
2)如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:
实例:如果A表是大表,B表是小表,
则应该按照如下方法使用in和exist
1)select * from A where id in (select id from B where A.id = B.id);
2)select * from B where exist (select * from A where A.id = B.id);

4、不同点:
in查询的子条件返回结果必须只有一个字段,例如
select * from user where userId in (select id from B);
而不能是
select * from user where userId in (select id, age from B);
而exists就没有这个限制

参考:
http://www.cnblogs.com/weiyi1314/p/6489236.html
http://blog.csdn.net/wudongxu/article/details/6966052

posted @ 2017-05-08 16:33  一缕炊烟  阅读(782)  评论(0编辑  收藏  举报