mysql——查询优化,重中之重

1. 查询语句尽量不要使用 select *

原因说明:

  1. 节省资源,减少网络开销,* 是所有字段,无用的字段只会增加网络消耗

  2. select* 杜绝了覆盖索引的可能性,基于MySQL优化器的“覆盖索引”策略又是速度极快,效率极高,业界极为推荐的查询优化方案

📌 反例


select * from user_info

📌 正例

select id,name,sex from user_info

2. 尽量避免在where 中使用or 拼接

原因说明:

1.最主要原因会是索引失败,走全表扫码

📌 反例

select id,name,sex from user_info where id =1 or sex = 0

📌 正例

  1. 使用union all
select id,name,sex from user_info where id =1 
UNION ALL 
select id,name,sex from user_info where sex =0 
  1. 分开查询
select id,name,sex from user_info where id =1 

select id,name,sex from user_info where sex =0

3. 模糊查询,优化like语句

在模糊查询中使用,使用like语句得注意,like很有可能让索引失效

📌 反例


select id,name,sex from user_info where name like '%Java资讯' 

select id,name,sex from user_info where name like '%Java资讯%'

这两种 模糊匹配都是不走索引的 (按需求来,有时候不得不)

📌 正例

select id,name,sex from user_info where name like 'Java资讯%'

4. 尽量避免在where字句中使用!= 或 <> 操作符

主要原因是会放弃索引,走全表扫描

比如:


select id,name,sex from user_info where name <> 'Java资讯'
或
select id,name,sex from user_info where name != 'Java资讯'

这也不能说是反例,要是需求,也是迫不得已,实在没有别的方案,只能使用,只是说尽量避免使用

5. where 中要使用默认值 比如 0 代替null

可能会导致引擎放弃索引,走全文扫描

📌 反例


select id,name,sex from user_info where sex is NOT NULL

📌 正例


select id,name,sex from user_info where sex >=0

6. 当只需要一条语句时加上 limit 1

📌 正例


select id,name,sex from user_info where name like 'Java资讯%' limit 1 

7.尽量避免使用 In 或 not In ,对于连续的数字我们可以使用BETWEEN

📌 正例


select id,name,sex,age from user_info where age between 20 and  25

如果in 里面内容不连续并且 过于 庞大,我们可以使用多线程查询 (进行分批再组装)

8. 尽量避免使用mysql 中的复杂函数

9. join 查询联表不超过7 个 一般 3 个左右适宜 (其他用代码处理)

10. 索引并不是越多越好

  • 索引虽然可以提升select 效率,但是也降低了 insert和update 效率,所以建立索引要慎重
  • 一个表索引数不要超过6 个,数据量小的表不要建立索引

11.尽可能的使用 varchar/nvarchar 代替 char/nchar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值