mysql 的基础sql 优化

  1. 避免全表扫描
    对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 orderby 涉及的列上建立索引

  2. 避免判断 null 值
    应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如
    selec tid from test where num is null
    可以在 num 上设置默认值 0,确保表中 num 列没有 null 值,然后这样查询
    select id from test where num = 0

  3. 避免不等值判断
    应尽量避免在 where 子句中使用!=或<>操作符,否则引擎将放弃使用索引而进行全表扫描。

  4. 避免使用 or 逻辑
    应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进 行全表扫描,如:
    select id from test where id= 1or id= 2
    可以这样查询:
    select id from test where id= 1 union all select id from test where id= 2
    union all不再创建临时表,这样在联合查询时会减少I/O开销

  5. 慎用 in 和 notin 逻辑
    in 和 notin 也要慎用,否则会导致全表扫描,如:

    select id from testA where id in ( selec tid from testB where id > 10)
    此时外层查询会全表扫描,不使用索引。可以修改为:
    select id from testA tA,( select id from testB where id > 10 ) tB where tA.id = tB.id

  6. 注意模糊查询
    下面的查询也将导致全表扫描:

    select id from t where name like '%abc%'
    模糊查询如果是必要条件时,可以使用
    select id from t where name like 'abc%'
    来实现模糊查询,此时索引将被使用。如果头匹配是必要逻辑,建议使用全文搜索引擎(Elasticsearch、 Lucene、Solr 等)。

  7. 避免查询条件中字段计算
    应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进 行全表扫描。如:

select id from t where num/2=100

应改为:

select id from t where num=100*2

  1. 避免查询条件中对字段进行函数操作
    应尽量避免在 where 子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描。如:

select id from t where substring(name,1,3)='abc'--name

以 abc 开头的 id 应改为:

select id from t where name like 'abc%'

  1. WHERE 子句“=”左边注意点
    不要在 where 子句中的“=”左边进行函数、算术运算或其他表达式运算,否则系统 将可能无法正确使用索引。

  2. 组合索引使用
    在使用索引字段作为条件时,如果该索引是复合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使用,并且应尽可能的让字段顺序与索引顺序相一致。

  3. exists
    很多时候用 exists 代替 in 是一个好的选择:
    select num from a where num in(select num from b)
    用下面的语句替换:
    select num from a where exists(select 1 from b where num=a.num)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值