1、查询SQL尽量不要使用select *,而是select具体字段。
反例子:
select * from employee;
正例子:
select id,name, age from employee;
- select具体字段,节省资源、减少网络开销。
- select * 进行查询时,很可能就不会使用到覆盖索引了,就会造成回表查询。
2、应尽量避免在where子句中使用or来连接条件
反例:
select * from user where userid=1 or age =18
正例:
//使用union all
select * from user where userid=1
union all
select * from user where age = 18
//或者分开两条sql写:
select * from user where userid=1
select * from user where age = 18
- 使用or可能会使索引失效,从而全表扫描。一位朋友踩过这个坑,差点把数据库CPU打满了。
如果userId加了索引,age没加索引,以上or的查询SQL,假设它走了userId的索引,但是走到age查询条件时,它还得全表扫描,也就是需要三步过程: 全表扫描+索引扫描+合并。如果它一开始就走全表扫描,直接一遍扫描就完事。mysql是有优化器的,处于效率与成本考虑,遇到or条件,索引可能失效,看起来也合情合理。
3. 尽量使用limit,避免不必要的返回
假设一个用户有多个订单,要查询最新订单的下单时间的话,你是这样查询:
select id, order_date from order_tab
where user_id=666
order by create_date desc;
获取到订单列表后,取第一个的下单时间:
List<Order> orderList = orderService.queryOrderListByUserId('666');
Date orderDate = orderList.get(0).getOrderDate();
还是用limit ,只获取最新那个订单返回:
select id, order_date from order_tab
where user_id=666
order by create_date desc limit 1;
显然,使用limit的更好~ 因为整体性能更好。
4. 尽量使用数值类型而不是字符串
比如我们定义性别字段的时候,更推荐0代表女生,1表示男生,而不是定义为WOMEN 或者MAN的字符串。
因为:
- 数值类型(如 INT, FLOAT, DECIMAL 等)通常占用的存储空间比字符串类型(如 VARCHAR, CHAR)小
- 数值类型的比较和计算速度通常比字符串快
5. 批量操作(更新、删除、查询)
反例:
for(User u :list){
INSERT into user(name,age) values(#name#,#age#)
}
正例:
//一次500批量插入,分批进行
insert into user(name,age) values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.name},#{item.age})
</foreach>
理由:
- 批量插入性能好,更加省时间
打个比喻: 假如你需要搬一万块砖到楼顶,你有一个电梯,电梯一次可以放适量的砖(最多放500),你可以选择一次运送一块砖,也可以一次运送500,你觉得哪个时间消耗大?
6、尽量用 union all 替换 union
如果检索结果中不会有重复的记录,推荐union all 替换 union。
反例:
select * from user where userid=1
union
select * from user where age = 10
正例:
select * from user where userid=1
union all
select * from user where age = 10
理由:
- 如果使用union,不管检索结果有没有重复,都会尝试进行合并,然后在输出最终结果前进行排序。如果已知检索结果没有重复记录,使用union all 代替union,这样会提高效率。

最低0.47元/天 解锁文章
1420

被折叠的 条评论
为什么被折叠?



