索引和拆分表可以极大的增加查询速度
我们的在写sql的时候也可以通过优化来增加查询速度.
-
对查询进行优化,要尽量避免全表扫描,首先应考虑在where和order by 涉及的列上建立索引.
-
应尽量避免在where子句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描.如:
select * from table where colum is null
最好不要给数据库留null,尽可能使用NOT NULL填充数据
备注,描述,评论之类的可以设置为NULL,其他的最好不要使用NULL
尽量使用varchar,因为NULL在char类型就会占所设置的字符数.在varchar中NULL不会占用空间
可以 对于数字类型的直接设置为0 -
应尽量避免在where子句中使用 != 或 <> 操作符,否则将引擎放弃使用索引而进行全表 扫描
-
应尽量避免在where子句中使用 or 来连接条件,如果一个字段有索引,一个字段无索引,会导致引擎放弃使用索引,
如: select * from table where age=10 or name=‘wlx’
可以改成
select * from table where age=10 union all
select * from table where name=‘wlx’. -
in 和 not in 也要慎用,否则会导致全表扫描,如
select * from table where age in (1,2,3);
对于连续的数值我们可以用 between 不用 in
select * from table where age between 1 and 3
很多时候用 exists 代替 in
select * from table1 where age in (select age from table2); 可以用一下语句替换
select * from table1 t1 where exists(select age from table2 where age=t1.age); -
下面的查询也 将导致全表扫描
select * from table where name like ‘%aaaa’;
若要提高效率,可以考虑全文检索 -
如果where子句中使用参数,也会导致全表扫描.因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择. 然而如果在编译时建立访问计划,变量的值还是未知的 ,因而无法作为索引选择的输入项.如果下面语句将进行全表扫描.
select * from table where age=@age
可以改为强制查询使用索引
select * from table with(index(索引)) where age =@age
应尽量避免在where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描.如
select * from table age/2=11 可以改为
select * from table age=11*2 -
应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描.如
select * from table substring(name,1,3) = ‘abc’; //查询name以abc开头的数据
select * from table where datediff(createdate,‘2019-07-04’)=0 //查询createdate和2019-07-04相等的数据
可以改为 select * from table where name=‘ABC%’
select * from table where createdate>=2019-07-04 and createdate< 2019-07-04