Mysql 查询优化

1、对查询进行优化,应尽可能避免全表扫描,首先应考虑在 where 及 where and  order by 涉及的列上创建索引。索引字段添加原则是 经过某个字段来 查询排序检索数据库时 应该加索引提升效率sql

 2、应尽可能避免在 where 子句中对字段进行 null 值判断,不然将致使引擎放弃使用索引而进行全表扫描,如:  数据库

select id from t where num is null

  能够在num上设置默认值0,确保表中num列没有null值,而后这样查询: 优化

select id from t where num=0

   这就是为何在设计数据库的时候 要把全部字段都设置默认值,而不是null的缘由
spa

3、应尽可能避免在 where 子句中使用!=<>操做符,不然将引擎放弃使用索引而进行全表扫描。
设计

 

4、应尽可能避免在 where 子句中使用 or 来链接条件,不然将致使引擎放弃使用索引而 进行全表扫描,如:code

  select id from t where num=10 or num=20排序

  能够这样查询:索引

  select id from t where num=10io

  union allclass

  select id from t where num=20

 

5in 和 not in 也要慎用,不然会致使全表扫描,如:

  select id from t where num in(123)

  对于连续的数值,能用 between 就不要用 in 了:

  select id from t where num between 1 and 3

 

6、下面的查询也将致使全表扫描:

  select id from t where name like '%abc%'

  若要提升效率,能够考虑全文检索。

 

7、应尽可能避免在 where 子句中对字段进行表达式操做,这将致使引擎放弃使用索引而进行全表扫描。如:

  select id from t where num/2=100

  应改成:

  select id from t where num=100*2

相关文章
相关标签/搜索