我们经常会遇到两种情况:
索引失效的场景汇总如下:
select *
%
not in
和not exist
CREATE TABLE example
(
id int NOT NULL AUTO_INCREMENT,
code varchar(20) DEFAULT NULL,
age int DEFAULT 0,
name varchar(30) DEFAULT NULL,
height int DEFAULT 0,
PRIMARY KEY (id),
KEY idx_code_age_name (code, age, name),
KEY idx_height (height)
);
INSERT INTO example (id, code, age, name, height, address)
VALUES (1, '10', 21, '张三', 175, '北京');
INSERT INTO example(id, code, age, name, height, address)
VALUES (2, '11', 18, '李四', 173, '上海');
INSERT INTO example (id, code, age, name, height, address)
VALUES (3, '12', 23, '王武', 174, '广州');
INSERT INTO example (id, code, age, name, height, address)
VALUES (4, '13', 22, '马六', 154, '重庆');
创建了三个索引
查看执行计划,可以使用explain
关键字,例如:
explain select * from example where id=1;
执行结果:
从图中可以看出,由于id字段是主键,该SQL语句用到了主键索引
select *
explain
select * from example where name='苏三'