system > const > eq_ref > ref > range > index > all
优化级别从左往右递减,没有索引的⼀般为’all’。推荐优化目标:至少要达到 range 级别, 要求是 ref 级别, 如果可以是 const 最好;index比all更优,但是并不明显,性能都很差。
这是const类型的特列,实际开发中难以达到(基本不会出现)。
实例
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_name_IDX` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
explain select * from `user` u where id=1
explain select * from `user` u where name='zhangsan'
实例
CREATE TABLE `user_job` (
`id` int(11) NOT NULL,
`userId` int(11) NOT NULL,
`job` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`) USING BTREE,
KEY `user_job_userId_IDX` (`userId`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
explain select uj.id ,u.name ,uj.job from user_job uj left join `user` u on uj.userId =u.id
实例
CREATE TABLE `user_job` (
`id` int(11) NOT NULL,
`userId` int(11) NOT NULL,
`job` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`) USING BTREE,
KEY `user_job_userId_IDX` (`userId`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
explain select * from user_job uj where name ='xx'
实例
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_name_IDX` (`name`) USING BTREE,
KEY `user_age_IDX` (`age`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
explain select * from `user` u where id>1
explain select * from `user` u where name in('zhangsan','lisi')
explain select * from `user` u where age BETWEEN 10 and 20
explain select id,name from `user` u
explain select age from `user` u
explain select * from `user` u