看到很多网上谈优化mysql的文章,发现很多在谈到mysql的null是不走索引的,在此我觉得很有必要纠正下这类结论。
mysql is null是有索引的,而且是很高效的,(版本:mysql5.5)
表结构如下:
CREATE TABLE `student` ( `stu_no` int(2) unsigned zerofill NOT NULL AUTO_INCREMENT COMMENT '学员编号', `stu_name` varchar(30) CHARACTER SET utf8 DEFAULT NULL COMMENT '学员姓名', `stu_sex` varchar(3) CHARACTER SET utf8 NOT NULL COMMENT '学员性别', `stu_age` tinyint(2) unsigned zerofill DEFAULT NULL COMMENT '学员年代', `grade` double(5,2) unsigned zerofill DEFAULT NULL COMMENT '成绩', `class_no` int(2) unsigned zerofill DEFAULT NULL COMMENT '所在班级编号', PRIMARY KEY (`stu_no`), KEY `class_no` (`class_no`), KEY `stu_name` (`stu_name`) COMMENT '学生姓名索引' ) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;
测试几条数据:
INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('01', '李白', '男', '18', '60.00', '01'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('02', '杜甫', '男', '20', '76.00', '01'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('03', '张飞', '男', '32', '80.00', '02'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('04', '韩信', '男', '26', '98.00', '02'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('05', '了龙', '男', '27', '56.00', '02'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('06', '大乔', '女', '17', '88.00', '01'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('07', '小乔', '女', '16', '96.00', '01'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('08', '小乔', '女', '16', '90.00', '01'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('09', '关哥', '男', '32', '80.00', '02'); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('10', '刘备', '男', '36', '98.00', NULL); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('11', '宋江', '男', '37', NULL, NULL); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('12', '李逵', '', '27', NULL, NULL); INSERT INTO `test`.`student` (`stu_no`, `stu_name`, `stu_sex`, `stu_age`, `grade`, `class_no`) VALUES ('13', NULL, '女', '21', '39.00', '01');
可以看到使用了索引stu_name,ref=const,索引效率还是很高的。