1. 尽量避免在字段开头模糊查询,会导致数据库引擎放弃索引进行全表扫描
select * from user where name like ‘%晓%’
优化方式:尽量在字段后面使用模糊查询
select * from user where name like ‘晓%’
2. 查询条件不能用 <> 或者 !=
3. order by 条件要与where中条件一致,否则order by不会利用索引进行排序
不走索引
select * from user oder by age
走索引
select * from user where age > 0 order by age
4. 避免出现select *的出现
select*会将所有数据的列全部取出,应该根据业务的实际需求取出对应的列
select * from user where age > 5
正确写法:
select id name age from user where age > 5
5. 使用表的别名,当在SQL语句中连接多个表时,请使用表的别名并把别名前缀于每个列名上。这样就可以减少解析的时间并减少哪些列名歧义引起的语法错误
6. 避免在where条件中等号的左侧进行表达式,函数操作
select * from user age-2 = 10
正确写法:
select * from user age = 10 + 2
7. 尽量避免null值的判断
select * from user where name = null
正确写法: 将name的默认值设置为0
select * from user where name = 0
8. 尽量避免使用or
select * from user where age = 1 or age = 2
正确写法:
select * from user where age = 1
union all
select * from user where age = 2
9. 尽量避免使用in和not in
select * from user where id in (2,3)
正确写法:
select * from user where id between 2 and 3
10. 使用varchar代替char
因为varchar是变长类型,char是定长类型
11. 字符串应该带上引号
未走索引
select * from user where name = 张三
走索引
select * from user where name = ‘张三’
12. 不要超过5个表以上的连接
13. 尽量使用union all替代union
union会将最后结果的重复数据去掉,而union all则是将所有数据全部返回,不管是否有重复数据