数据库SQL

数据库系列4 SQL优化

2019-02-28  本文已影响0人  莫小归

参考:
关于基数、选择性、直方图和回表 https://www.jianshu.com/p/44ebb7646b34
关于SQL优化的误区和小技巧 https://www.jianshu.com/p/8a4d8f1ccc56
关于逻辑算子 http://www.imooc.com/article/278660

一.SQL优化

1.目的
2.技巧
3.SQL优化场景

二.几个概念

1.基数(Cardinality)
2.选择性(Selectivity)
3.直方图(Histogram)
4.回表(Table Access By Index RowId)
5.逻辑算子
6.逻辑查询计划
select user.name from user,score where user.id = score.id and score.num > 60

变成查询计划之后如图所示:
1)DataSource,user,score表,负责读取数据。
2)Join,user.id=score.id
3)Selection过滤,score.num > 60
4)Projection投影,user.name

三.常见误区

1.count(1)和count(primary_key)优于count(*)
2.count(column)和count(*)是一样的
3. select a,b from ... 比 select a,b,c from ...可以让数据库返回更少的数据量
4. order by 一定需要排序操作

四.关于索引的SQL语句优化技巧

1.尽量避免在where子句中使用 > 、<、!= 等范围操作符,否则数据库引擎将放弃索引进行全表扫描
2.尽量避免在where子句中使用 or 条件,或使用union或者in代替or,否则数据库引擎将放弃索引进行全表扫描
select id from t where num=10 or num=20 
select * from t where LOC_ID = 10 or LOC_ID = 20 or LOC_ID = 30;
select id from t where num=10 union all select id from t where num=20
select * from t where LOC_IN in (10,20,30);
3.慎用 in 和 not in
SELECT * FROM ACCOUNT
    WHERE AC_CODE 
    NOT IN (
              SELECT CODE
              FROM GOODS
              WHERE NUM='001')       //低效

SELECT * FROM ACCOUNT
    WHERE NOT EXISTS
       (SELECT CODE
          FROM GOODS
          WHERE CODE=ACCOUNT.AC_CODE
           AND NUM='001')             //更高效
4. like %aaa% 语句将导致全表扫描
5.避免在 where 子句进行表达式操作
select id form t where num/2 = 100
select id from t where num = 200
6.避免在 where 子句对字段进行函数操作
select id from t where substring(name,1,3) = 'abc'
select id from t where name like 'abc%'
7.where字句中的连接顺序
select * from table e
      where h>500     
                  and d='001'
                  and 25<(select count(*) 
                               from table 
                               where count=e.count);      //低效

select * from table e
      where  25<(select count(*) 
                          from table 
                          where count=e.count);    
                   and  h>500
                   and d='001';                            //更高效 
8.

五.关于SQL语句执行顺序的优化

1.语法顺序和执行顺序
select [distinct]...from...[xxx join][on]...where...group by...having...[union]...order by...
from...[xxx join][on]...where...group by...sum()...having...select [distinct]...order by....
2.from 子句
3.where子句

4.group by 和order by 子句

5.select子句

六.查询优化器

1.查询优化器分类
2.查询优化器执行过程
3.查询优化器常见优化规则(自动执行)
//优化前
EXPLAIN SELECT *
FROM t_student,t_score
WHERE t_score.student_id=t_student.student_id
AND t_score.score_id=2;
//优化后
EXPLAIN SELECT * FROM t_student t1 right JOIN (
SELECT * from t_score WHERE score_id=2
) t2
ON t1.student_id=t2.student_id;
//优化前
select max(id) from table1
//优化后
select max(id) from (select id from table1 order by id desc limit 1 where id is not null) t

一个具体Sql优化实例 https://www.jianshu.com/p/0b1571730d3f
待续

上一篇下一篇

猜你喜欢

热点阅读