再谈SQL优化的基本操作

1.where条件左多又少原则

原则,多数数据库都是从左到右的顺序处理条件,把能过滤更多数据的条件放在前面,过滤少的条件放后面
SQL1: select * from employee
where salary >1000 --条件1,过滤的数据较少
and dept_id='01' --条件2,过滤的数据比条件1多

上面的SQL就不符合我们的原则了,应该把过滤数据更多的条件放在前面,因此改为下面这样更好

select * from employee
where dept_id='01' --过滤更多数据的条件放在前面
and salary > 1000

2.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索 limit 控制条数;
Limit限制的是从结果集的M位置处取出N条输出,其余抛弃.

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

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

5.应尽量是使用union all;而避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,
如:select id from t where num=10 or num=20
可以这样查询:
select id from t where num=10
union all
select id from t where num=20

6.in 和 not in 也要慎用,否则会导致全表扫描;用between,
如:select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3

7.应尽量避免在 where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描。如:
select id from t where num/2=100
应改为:
select id from t where num=100*2

8.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)

9.索引并不是越多越好,索引固然可以提高相应的 select 的效率,但同时也降低了 insert 及
update 的效率,因为 insert 或 update
时有可能会重建索引,所以怎样建索引需要慎重考虑,视具体情况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。

10.应尽可能的避免更新聚簇索引clustered 索引数据列,因为 clustered
索引数据列的顺序就是表记录的物理存储顺序,一旦该列值改变将导致整个表记录的顺序的调整,
会耗费相当大的资源。若应用系统需要频繁更新 clustered

-----------------------------------------------------------------------------------------------------------------

案例一:利用临时表的索引字段;做子查询如 userid>(select userid from user limit 10000,1) 表示取ID是大于等于>=10001以后的数据 20条做分页

SELECT * FROM product WHERE ID > =(select id from product limit 866613, 1) limit 20
查询时间为0.2秒!

另一种写法
SELECT * FROM product a JOIN (select id from product limit 866613, 20) b ON a.ID = b.id
查询时间也很短!

测试示例:
SELECT * from t_banksite_code where banksiteid>= (SELECT banksiteid from t_banksite_code limit 15100,1) limit 1000;

 

posted @ 2019-05-22 23:06  王默默  阅读(211)  评论(0编辑  收藏  举报