在编码过程中编写sql语句是不可避免的,编写出高质量的SQL语句对系统的使用有着重要的影响,今天就来介绍mysql查询优化的9中方法,希望在以后的编码中避免下文中出现的不好的方式。

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

2.应尽量i避免在where子句中对字段进行NULL值判断,否则将导致引擎放弃使用索引而进行全表扫描,eg:

select id from table1 where num is null;

可以在num上设置默认值为0,确保表中num列没有null值,然后这样查询:

select id from table1 where num = 0;

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

     4.应尽量避免在where子句中使用or来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,eg:

select id from table1 where num = 10 or num = 20;

可以这样查询:

select id from table1 where num = 10

union all

select id from table1 where num = 20;

5.in和not in 也要慎用,否在会导致全表扫描,eg:

select id from table1 where num in(1,2,3);

对于连续的数值,能用between就不要用inle;

select id from table1 where num between 1 and 3;

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

select id from table1 where name like “%OO%”;

若要提高效率,可以考虑全文检索;

7.如果在where子句中使用参数,也会导致全表扫描。因为sql只有在运行时才会解析局部变量,但优化程序不能访问计划的选择推迟到运行时;它必须再编译时进行选择。然而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。如下面语句将进行全表扫描:

select id from table1 where num = @num;

可以改为强制查询使用索引:

select id from table1 with(index(索引名)) wherenum = @num;

8.应尽量避免在where子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。eg:

select id from table1 where num/2 =100;

应改为:

select id from table1 where num = 100*2;

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

select id from table1 where substring(name,1,3)=‘ooo’;

select id from table1 where datediff(day,createdate,'2015-10-30')=0;