使用explain分析sql语句

mac2022-06-30  90

sql语句优化 1: sql语句的时间花在哪儿? 答: 等待时间 , 执行时间. 这两个时间并非孤立的, 如果单条语句执行的快了,对其他语句的锁定的也就少了. 所以,我们来分析如何降低执行时间. 2: sql语句的执行时间,又花在哪儿了? 答: a: 查 ----> 沿着索引查,甚至全表扫描 b: 取 ----> 查到行后,把数据取出来(sending data) 3: sql语句的优化思路? 答: 不查, 通过业务逻辑来计算, 比如论坛的注册会员数,我们可以根据前3个月统计的每天注册数, 用程序来估算. 少查, 尽量精准数据,少取行. 我们观察新闻网站,评论内容等,一般一次性取列表 10-30条左右. 必须要查,尽量走在索引上查询行. 取时, 取尽量少的列. 比如 select * from tableA, 就取出所有列, 不建议. 比如 select * from tableA,tableB, 取出A,B表的所有列. 4: 如果定量分析查的多少行,和是否沿着索引查? 答: 用explain来分析 explain的列分析 id: 代表select 语句的编号, 如果是连接查询,表之间是平等关系, select 编号都是1,从1开始. 如果某select中有子查询,则编号递增. mysql> explain select goods_id,goods_name from goods where goods_id in (sele ct goods_id from goods where cat_id=4) \G *************************** 1. row *************************** id: 1 select_type: PRIMARY table: goods type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: 31 Extra: Using where---------------------------------------------------------------------参数解释:

select_type: 查询类型

 

table: 查询针对的表

有可能是

实际的表名  如select * from t1;

表的别名    如 select * from t2 as tmp;

derived      如from型子查询时

null         直接计算得结果,不用走表

possible_key: 可能用到的索引

注意: 系统估计可能用的几个索引,但最终,只能用1个.

key : 最终用的索引.

key_len: 使用的索引的最大长度

ref: 指连接查询时, 表之间的字段引用关系.

rows: 是指估计要扫描多少行.

extra: 利用到了哪些索引,可能的值有

(1)index: 是指用到了索引覆盖,效率非常高

(2)using where 是指光靠索引定位不了,还得where判断一下

(3)using temporary 是指用上了临时表, group by 与order by 不同列时,或group by ,order by 别的表的列.

(4) using filesort : 文件排序(文件可能在磁盘,也可能在内存)

type列: 是指查询的方式, 非常重要,是分析”查数据过程”的重要依据

可能的值

(1) all:  意味着从表的第1行,往后,逐行做全表扫描.,运气不好扫描到最后一行. (2) index: 比all性能稍好一点,通俗的说: all 扫描所有的数据行,相当于data_all  index 扫描所有的索引节点,相当于index_all (3) range: 意思是查询时,能根据索引做范围的扫描 如sql:

  explain select goods_id,goods_name,shop_price from  goods where goods_id >25 \G

(4) ref  意思是指 通过索引列,可以直接引用到某些数据行 如sql:explain select goods_id,goods_name from  goods where cat_id=4 \G(5) eq_ref 是指,通过索引列,直接引用某1行数据 常见于连接查询中

  explain select goods_id,shop_price from  goods innert join ecs_categoy using(cat_id) where goods_id> 25 \G

(6) const, system, null  这3个分别指查询优化到常量级别, 甚至不需要查找时间.

  一般按照主键来查询时,易出现const,system 或者直接查询某个表达式,不经过表时, 出现NULL

  explain select goods_id,goods_name,click_count from  goods wher_id=4 \G

 

转载于:https://www.cnblogs.com/hgj123/p/5032444.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)