SQL语句优化
-
在where 和 order by 中使用索引字段
-
where 子句中 避免使用<> !=也不要进行 is null 判断,否则会放弃索引
-
where 子句中 使用or需要左右均使用索引,否则放弃使用索引
-
where 子句中 不要再 = 左边进行函数、算术运算或其他表达式运算
-
避免使用模糊查询(like %a)
-
如果 in 中为连续数值,建议使用between
-
避免使用 ‘*’ 应选择需要返回的字段
-
有时候使用 exists 代替 in 是一个好的选择:
select num from a where num in(select num from b)
用下面的语句替换:
select num from a where exists(select 1 from b where num=a.num)
索引优化
-
索引建立应选择经常作查询选择的字段、经常作表连接的字段以及经常出现在order by、group by、distinct 后面的字段
-
索引会提升 select 效率,同时降低 insert 和 update 效率,所以应选择合适字段建立索引
-
联合索引最左匹配原则
创建临时表的几种情况
- UNION查询;
- 用到TEMPTABLE算法或者是UNION查询中的视图;
- ORDER