经常使用mysql,然后就有一些sql的优化,可以帮忙性能的提升
1、条件where,group by ,order by后面尽量使用索引,否则是全表扫描。
2、模糊查询like不能都用%包围,最好就在后面使用,否则会让索引失效。
错误:where id like %xxx%;
正确:where id like xxx%;
3、使用in范围查询的地方,尽量改成between。
错误:where id in (2,3);
正确:where id between 2 and 3;
4、in使用子查询时候,子查询只是返回是否存在FALSE,TRUE,不返回记录时候,使用exsts,判断是否存在记录。
错误:where id in (select x from xx where i =xxx);
正确:where id exists (select x from xx where i =xxx);
5、尽量不要在条件后使用or,改成union。
错误:where id =3 or id =4;
正确:where id =3 union where id =4;
6、一些情况下使用>=代替>。
eg:where id >3;
正确:where id >=4;
7、尽量不要在where后面判断字段=null,会变成全表扫描了。
8、在where条件中,=号左边不要使用函数,表达式计算等,换到右边。
eg:where id/2=50;
正确:where id = 50*2;
9、特殊字符>,<,!=等使用mybatis的CDATA包围起来。不能直接使用,否则会被让引擎的索引失效。
10、索引不要超过6个,超过就要检视哪些索引不是必须的了,创建太多索引会让查询速度变很慢的。