1. 给where、group by 条件字段加索引
select t.a, t.b, t.c from t where t.e = 0 group by t.f
2. 避免使用 select * from
示例:
select * from table t;
推荐写法 :
select t.a, t.b, t.c from table t;
3. 使用 where exists 替代 in
示例:
select t.a, t.b, t.c from table t where t.id in (1,2,3,4,5);
推荐写法:
select t.a, t.b, t.c from table t where t.id exists (
select t.id from table2 t2 where t2.name = "一年级一班"
);
4. 使用 union 替代 or
示例:
select t.a, t.b, t.c from table t where t.name = "张三" and t.age = 20 or t.phone = 110;
推荐写法:
select t.a, t.b, t.c from table t where t.name = "张三" and t.age = 20
union
select t.a, t.b, t.c from table t2 where t2.name = "张三" and t.phone = 110
5. 使用 like li% 替代 like %li%
示例:
select t.a, t.b, t.c from table t where t.name like %杰%;
推荐写法:
select t.a, t.b, t.c from t where t.name like 杰%;
6. 避免使用 null 判断,例如:is null 或者 is not null
示例:
select t.a, t.b from table t where t.c is null;
推荐写法:
设置t.c 字段默认值为 : 0;
select t.a, t.b, t.c from table t where t.c = 0;
7. 避免where 左侧使用函数和表达式
示例:
select t.a, t.b, t.c from table t where t.number / 10 > 5;
推荐写法:
select t.a, t.b, t.c from table t where t.number > 5 * 10;
8. 避免使用where 1=1 ,使用where 标签替换
示例:
<select id="findAll" paramterType="java.util.String" resultType="java.util.Map">
select t.a, t.b, t.c from table t
<where>
<if test="state != null">
and t.state = #{state}
</if>
</where>
</select>
推荐写法:
<select id="findAll" paramterType="java.util.String" resultType="java.util.Map">
select t.a, t.b, t.c from table t
where 1 = 1
<if test="state != null">
and t.state = #{state}
</if>
</select>
9. 表字段能设置用数字类型替代字符类型
10. 减少数据库访问次数,用批量执行减少访问数量
11. SQL语句用大写,oracle是将SQL转大写后执行
12. 关联查询时数据较少的表放在数据较多表的右边
13. 涉及多列无主键时,count(1) 性能优于 count(*)
14. 避免使用多数据使用游标遍历,建议改写SQL
15. 避免返回大批量数据到客户端,建议使用后台分页
16.合理使用数据库索引:
添加索引可以提高select效率,但是同时也会降低update和insert 效率。因为涉及数据新增和修改会重新创建索引。
17.使用varchar类型替代char类型
char类型占用存储空间大于varchar类型,使用相对较小的字段查询效率较高。