SQL优化策略
1. 給where、group by 條件字段加索引
select t.a, t.b, t.c from t where t.e = 0 group by t.f2. 避免使用 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 = 1105. 使用 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 twhere 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
總結
- 上一篇: spring boot 微服务集群 +
- 下一篇: 为什么不能在SQL拼接模糊匹配符号