MySQL查询条件中in会用到索引吗

当用人问你MySQL 查询条件中 in 会不会用到索引,你该怎么回答?

答案:可能会用到索引

动手来测试下

1.创建一张表,给字段port建立索引

CREATE TABLE `pre_request_logs_20180524` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `ip` char(16) NOT NULL COMMENT '代理IP',
 `port` int(8) NOT NULL COMMENT '端口号',
 `status` enum('成功','失败') NOT NULL COMMENT '状态',
 `create_time` datetime NOT NULL COMMENT '创建时间',
 `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`),
 KEY `idx_port` (`port`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='代理IP请求日志';

插入测试数据

INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (1, '192.168.1.199', 53149, '失败', '2018-05-24 14:55:34', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (2, '192.168.1.100', 10653, '成功', '2018-05-24 14:55:54', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (3, '192.168.1.112', 50359, '失败', '2018-05-24 14:56:00', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (4, '192.168.1.67', 30426, '失败', '2018-05-24 14:56:09', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (5, '192.168.1.209', 49323, '失败', '2018-05-24 14:56:12', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (6, '192.168.1.209', 51161, '成功', '2018-05-24 14:56:13', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (7, '192.168.1.12', 54167, '成功', '2018-05-24 14:56:16', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (8, '192.168.1.64', 20462, '成功', '2018-05-24 14:56:19', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (9, '192.168.1.53', 22823, '失败', '2018-05-24 14:56:31', '2018-11-16 10:58:13');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (10, '192.168.1.85', 48229, '成功', '2018-05-24 14:56:32', '2018-11-16 11:01:11');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (11, '192.168.1.85', 48229, '成功', '2018-05-24 14:56:32', '2018-11-16 11:01:15');
INSERT INTO ``(`id`, `ip`, `port`, `status`, `create_time`, `update_time`) VALUES (12, '192.168.1.85', 48229, '成功', '2018-05-24 14:56:32', '2018-11-16 13:34:37');

2.测试sql

explain select * from pre_request_logs_20180524 where port in (51161,20462,48229);

执行结果

MySQL查询条件中in会用到索引吗

从结果来看是没有用到索引,但不要着急下结论,再看二个sql

select * from pre_request_logs_20180524 where port in (51161,48229);
select * from pre_request_logs_20180524 where port in (51161,20462);

执行结果分别如下

MySQL查询条件中in会用到索引吗

MySQL查询条件中in会用到索引吗

可以看到第二条sql是用到了索引,二条sql的区别在于port值不一样,一个包含48229,一个包含20462

其实MySQL优化器会自动判断in是否走二级索引,也就是port字段的索引

总结

相关推荐