MySQL 代替in/not in 的sql语句
来源:互联网 发布:数据库创建用户 编辑:程序博客网 时间:2024/06/05 06:47
1.in和exists
in是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询,一直以来认为exists比in效率高的说法是不准确的。
如果查询的两个表大小相当,那么用in和exists差别不大;如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in。
一般情况下,主表中的数据要少,从表的数据要多。
例:table a(小表) 、table b(大表)
select * from a where id in(select in from b) -->效率低,用到了a表上id列的索引;select * from a where exists(select id from b where id=a.id) -->效率高,用到了b表上id列的索引。
与之相反:select * from b where id in(select id from a) -->效率高,用到了b表上id列的索引select * from b where exists(select id from a where id=b.id) -->效率低,用到了a表上id列的索引。
(1)性能的考虑此时就按子表大主表小用exist,子表小主表大用in的原则就可以.
(2)写法的不同, exist的where条件是: "...... where exist (..... where a.id=b.id)"
in的where条件是: " ...... where id in ( select id from......)"
2.not in和not exists
在做查询时,想要查询有联系的两张表,想得到结果是一张表有而另外一张表没有的数据时,我们通常会用not in:
select * from a where a.id not in (select id from b)
通常,我们会习惯性的使用not in,在数据比较少的时候是可以的,但是一旦数据量大了,not in的效率就会显得差了点。
因为not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。
所以无论那个表大,用not exists都比not in要快。
所以推荐使用not exists或者外连接来代替:
select * from a where not exists(select id from b where id=a.id)
或者select * from a left join b on a.id = b.id where b.id is null;
阅读全文
0 0
- MySQL 代替in/not in 的sql语句
- SQL语句中的NOT IN 的优化
- mysql 技巧:left join代替not in()
- 优化SQL语句:in 和not in的替代方案
- sql替换NOT IN语句
- sql语句优化之用EXISTS替代IN、用NOT EXISTS替代NOT IN的语句
- sql语句中in与exist not in与not exist 的区别
- sql语句中in与exist not in与not exist 的区别
- sql语句中in与exists not in与not exists的区别
- 在sql语句中替换Not In 的方法
- linq to sql生成not in语句的小技巧
- 在sql语句中替换Not In 的方法
- EXISTS 代替 in ,not EXISTS 代替 not in
- mysql IN NOT IN
- 替代sql的in,not in操作
- SQL语句(IN、NOT IN、COUNT、GROUP BY)
- Oracle SQL NULL 值对 IN/NOT IN语句的影响
- SQLServer 优化SQL语句:in 和not in的替代方案
- IIS日志自动删除 bat脚本
- “玲珑杯”线上赛 Round #15 咸鱼魔法记(尺取法)
- Struts2中配置默认Action
- Java 多线程并发编程之互斥锁 Reentrant Lock
- unity3d中OnMouseEnter事件没有反应的解决办法
- MySQL 代替in/not in 的sql语句
- SDUT-1206 求三角形面积
- freemarker入门大全
- msmtp详细安装及使用
- 基于Retrofit、OkHttp、Gson封装通用网络框架
- volatile和synchronized特点
- 计算机专业导论其二
- IGBT知识
- 产后恢复完美容颜的健康食谱