show index form table_name:
Cardinality 在某列上不重复值的数量,对索引而言该值越大越好
seq_index 代表列在复合索引中的序号
analyze table user_profile; 触发采样
> 5.6 show create table table_name 不触发
创建索引:
-
高选择性的字段
-
不重复值较多的列
-
不带order by 的查询并不是按照主键排序的
-
复合索引(a, b) 会对a进行排序,但不会对b进行排序
索引使用分析:
select * from xxx where a = ? (yes)
select * from xxx where a = ? and b = ? (yes)
select * from xxx where a = ? or b = ? (no)
分析: or拿到是a 和 b 查询结果的并集,即使a用到了索引,但b仍然要全表扫描,所以并不会先用索引再扫描全表select count(1) from buy_log where buy_date >= ‘2011-01-01’ and buy_date < ‘2011-02-01’ (yes)
这个查询使用到复合索引(userid, buy_date):why here using the compound index?
在索引覆盖的场景下有时候可以用到复合索引,这要求根据b列查找数据能得到想要的数据,例如上例中我们根据时间来统计数量,通过扫描索引就可以得到结果不必走全表扫描了。
explain:
- 显示sql语句的执行计划
- 5.6版本支持DML语句
- 5.6开始支持JSON格式输出
show variables like ‘%not%using%’ 查看是否 开启没有使用索引的sql记录到慢查询日志
desc select statement == explain select statement
format=json 参数会显示cost info 等信息