文章目录
目录
前言
sql优化实战笔记
sql语句优化
一、in和exists哪个效率高
先看这两条sql,哪个效率更高呢?
select * from t_a a where a.id in (select id from t_b b where b.name=#{name});
select * from t_a a where exists (select id from t_b b where b.name=#{name} and a.id=b.id)
in 和exists
in是把外表和内表作hash 连接,而exists 是对外表作loop 循环,每次loop 循环再对内表进行查询。
一直以来认为exists 比in 效率高的说法是不准确的。如果查询的两个表大小相当,那么用in 和exists 差别不大。、
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:
not in 和not exists
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;
而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists 都比not in 要快。
二、查询条件哪个在前哪个在后
这个问题要考虑两方面的因素,
1、根据联合索引的前后顺序,尽量使用的锁索引,能全用上肯定最好
2、把最能过滤数据的条件放在前面
三、sql优化之如何改造or
条件中加这个or会导致索引的失效,当然就会使得查询效率的大幅下降
我们可以使用union或者union all来改造sql
注释:union:去掉重复的;union all:不去掉重复的
select * from t_a a where a.id = '1' or a.id = '2' or a.name = 'zhang';
select * from t_a a where a.id = '1'
union
select * from t_a a where a.id = '2'
union
select * from t_a a where a.name = 'zhang';
总结
仅做参考,所有修改后的sql都要经过自己实际的运行才能的到结论,切不可纸上谈兵