我有一个 zje 表
我先用一个普通的 select语句,用explain解析,看看有什么显示:
explain select * from zje;
主要关注的是,type 和 key:
type = ALL :表示全表扫描
type = const :表示通过索引一次就找到了
key = NULL:表示没有使用索引
key = primary :表示使用了主键
key一般=使用了主键/索引的名字
下面的图是使用了索引的:
select * from zje where math<60;
其中 key = math的 math就是索引名
假设有一张表,里面有一个复合索引:CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`gongzi` int(10) unsigned DEFAULT NULL,
`class_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `iname` (`name`),
KEY `classname` (`class_id`,`name`)
) ENGINE=MyISAM AUTO_INCREMENT=41 DEFAULT CHARSET=utf8 |
查询里面数据有
复合索引,遵循从左到有依次的原则。
explain select * from user where class_id=1 \G
explain select * from user where class_id>1 \G
第一个搜索条件必须是等于,不能使用区间范围 大小啊,否则索引失效。
复合索引不能使用区间,也不能使用不等于
mysql> explain select * from user where class_id!=1 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: user
type: ALL
possible_keys: classname
key: NULL
key_len: NULL
ref: NULL
rows: 40
Extra: Using where