bitscn.com
mysql查询分析器explain或desc mysql可以通过explain或desc来查看并分析sql语句的执行情况,如下需要计算2006年所有公司的销售额,需要关联sales表和company表,并且对money字段做求和操作,相应sql如下:
sql代码 explain select sum(money) from sales s,company c where s.company_id=c.id and s.year=2006 /g; *************************** 1. row *************************** id: 1 select_type: simple table: s type: all possible_keys: null key: null key_len: null ref: null rows: 1000 extra: using where *************************** 2. row *************************** id: 1 select_type: simple table: c type: ref possible_keys: index_company_id key: index_company_id key_len: 5 ref: sakila.c.company_id rows: 1 extra: using where; using index 列的说明: select_type: 表示select的类型,常见的有下面几种 simple: 简单表,不使用连接或子查询的 primary: 主查询,即外层的查询 union: union中的第二个或者后面的查询语句 subquery: 子查询中的第一个select table: 输出结果集的表 type: 表示表的连接类型,性能由好到差的连接类型为下面顺序 system: 表中只有一行,即常量表 const: 单表中最多有一个匹配行,如primary key或unique index eq_ref: 对于前面的每一行,在此表中只查询一条记录,也就是多表连接中使用primary key或unique index ref: 与eq_ref类似,区别在于不是使用primary key或unique index,而是使用普通索引 ref_or_null: 与ref类型,区别在于条件中包含对null的查询 index_merge: 索引合并优化 unique_subquery: in的后面是一个查询主键字段的子查询 index_subquery: 与unique_subquery类似,区别在于in的后面是查询非唯一索引字段的子查询 range: 单表中的范围查询 index: 对于前面的每一行,都通过查询索引来得到数据 all: 对于前面的每一行,都通过扫描全表来得到数据 possible_keys: 查询时可能用到的索引 key: 查询时实际使用到的索引 key-len: 索引字段的长度 rows: 扫描行的数量 extra: 执行情况的说明和描述 通过explain的分析,确认在上面的例子中是对sales表的全表扫描导致效率不理想,通过对sales表创建索引: sql代码 create index index_sales_year on sales(year); 创建索引后,再对该查询语句分析如下:sql代码 explain select sum(money) from sales s,company c where s.company_id=c.id and s.year=2006 /g; *************************** 1. row *************************** id: 1 select_type: simple table: s type: ref possible_keys: index_seles_year key: index_sales_year key_len: 2 ref: const rows: 1 extra: using where *************************** 2. row *************************** id: 1 select_type: simple table: c type: ref possible_keys: index_company_id key: index_company_id key_len: 5 ref: sakila.c.company_id rows: 1 extra: using where; using index bitscn.com