1. 避免频繁连接和关闭数据库,这样会导致IO访问次数太频繁。
  2. 设计表时要建立适当的索引,尤其要在 where 及 order by 涉及的列上建立索引
  3. 避免全表扫描,以下情况会导致放弃索引直接进行全部扫描
  • 避免在 where 子句中使用!=或<>操作符
  • 避免在 where 子句中对字段进行 null 值判断
    ​select id from table where num is null​
  • 解决方法:建表时设置默认值0,也就是将null用0填充,然后查询:

    ​select id from table where num=0​

  • 避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描
    ​select id from t where num=10 or num=20 ​​解决方法:使用 union
    ​select id from t where num=10 union all select id from t where num=20​
  • 避免使用 like
    ​select id from t where name like ‘%abc%’​​解决方法:使用全文检索
  • 避免使用 in 和 not in
    ​select id from t where num in(1,2,3)​
  • 解决方法1:连续值使用 between

    解决方法2:用 exists 替换 in

    ​select num from a where exists(select 1 from b where num=a.num)​

  • 避免使用参数
    ​select id from t where num=@num ​​解决方法:强制查询使用索引
    ​select id from t with(index(index_name)) where num=@num​
  • 避免表达式操作
    ​select id from t where num/2=100 ​​解决方法:​​select id from t where num=100*2​
  • 避免函数操作
    ​select id from t where substring(name,1,3)=’abc’ ​​ 查询以abc开头的id
    解决方法:全文索引