一、 表设计规范
二、 索引规范
虽然索引的可以提高查询的效率,但是在进行insert,update,和delete的时候会降低效率,因为在保存数据的同时也会去保存索引。
不要在一个表里建过多的索引,问题跟上面一样,在操作数据的时候效率降低,而且数据量少的表要看情况建索引,如果建索引跟没建索引的效果差不多少的情况下就不要建索引了,如果是数据量大的表,就需要建索引去优化查询效率。
此处引用https://www.cnblogs.com/zjfjava/p/6920407.html 致谢!
2.sql语句编写方面
select * 增加很多不必要的消耗(cpu,io,内存,网络带宽等);增加了使用覆盖索引的可能行;当表的结构发生修改时,前端也需要更新。所以要求直接在select后面接上字段名。尽量避免select * 这种操作,若不知可
select * from 表 limit 10;(只是查看对应表数可展示部分操作使用 limit函数)
当你查询表的有些时候,你已经知道结果只会有一条结果,但因为你可能需要去fetch游标,或是你也许会去检查返回的记录数。
在这种情况下,加上 LIMIT 1 可以增加性能。这样一样,MySQL数据库引擎会在找到一条数据后停止搜索,而不是继续往后查少下一条符合记录的数据。
这是为了使explain中type列达到const类型。
select id,name from product limit 866613, 20
select id,name from product limit 866613, 20
select * from student where name like ‘%三‘;
select * from student where reverse(name) like reverse(‘%三‘);
使用了索引,此方法能有效降低io次数。
3.避免在where子句中对字段进行表达式操作
select user_id,user_project from user_base where age*2=36;
可优化为:
select user_id,user_project from user_base where age=36/2;
4.应尽量避免在 where 子句中使用!=或<>操作符,否则将引擎放弃使用索引而进行全表扫描。
select id from student where id!=‘5‘;
5.应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描。
select id from t where num=10 or num=20
可以这样查询: select id from t where num=10 union all select id from t where num=20
6.in 和 not in 也要慎用,否则会导致全表扫描。
select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3
7.应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。
select id from t where substring(name,1,3)=’abc’–name
select id from t where datediff(day,createdate,’2005-11-30’)=0–‘2005-11-30’生成的id 应改为:
select id from t where name like ‘abc%’
select id from t where createdate>=’2005-11-30’ and createdate<’2005-12-1’
union和union all的差异主要是前者需要将结果集合并后再进行唯一性过滤操作,这就会涉及到排序,增加大量的CPU运算,加大资源消耗和延迟。
前提:union all是在两个结果集没有重复条件下,否则会有重复数据的。
9.避免隐式类型转换
比如a=1还是a=‘1‘
要提前确认数据格式,避免转换格式
10.如果排序字段没有用到索引,就尽量少排序
11.避免频繁创建和删除临时表,以减少系统表资源的消耗。
12.临时表并不是不可使用,适当地使用它们可以使某些例程更有效,例如,当需要重复引用大型表或常用表中的某个数据集时。但是,对于一次性事件,最好使用导出表。
13.在新建临时表时,如果一次性插入数据量很大,那么可以使用 select into 代替 create table,避免造成大量 log ,以提高速度;如果数据量不大,为了缓和系统表的资源,应先create table,然后insert。
14.通过explain查看sql执行计划
eg:
此博客介绍执行计划特别详细可以学习: https://www.cnblogs.com/klvchen/p/10137117.html
原文:https://www.cnblogs.com/workdata/p/15219863.html