SQL优化策略

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类型,使用相对较小的字段查询效率较高。

18. 避免在重复数据较多的列添加索引,可能会造成索引失效
19.避免大事务操作,提高并发性能
20.全表数据删除使用 truncate 替代 delete
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值