一、SQL语句优化
- 反向查询不能使用索引
select name from user where id not in (1,3,4);
select name from user where id in (2,5,6);
- 前导模糊查询不能使用索引
select name from user where name like '%zhangsan'
select name from user where name like 'zhangsan%'
- 数据区分不明显的不建议创建索引
- 字段的默认值不要为 null
- 在字段上进行计算不能命中索引
- 最左前缀问题
如果给 user 表中的 username pwd 字段创建了复合索引那么使用以下SQL 都是可以命中索引:
select username from user where username='zhangsan' and pwd ='axsedf1sd'
select username from user where pwd ='axsedf1sd' and username='zhangsan'
select username from user where username='zhangsan'
select username from user where pwd ='axsedf1sd'
- 如果明确知道只有一条记录返回
可以提高效率,可以让数据库停止游标移动。
select name from user where username='zhangsan' limit 1
- 不要让数据库帮我们做强制类型转换
- 如果需要进行 join 的字段两表的字段类型要相同