为什么在MySQL中select id比select *慢

问题描述

背景

我们正在使用mysql 5.6,并在网上遇到严重的缓慢查询。

表可以简化为

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',`job_id` bigint(11) NOT NULL DEFAULT '0',PRIMARY KEY (`id`),KEY `job_id` (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
| Field  | Type         | Null | Key | Default | Extra          |
+--------+--------------+------+-----+---------+----------------+
| id     | int unsigned | NO   | PRI | NULL    | auto_increment |
| name   | varchar(20)  | NO   |     |         |                |
| job_id | bigint       | NO   | MUL | 0       |                |
+--------+--------------+------+-----+---------+----------------+

一百万行,所有job_id为零。

我们创建名为job_id的{​​{1}}索引。

job_id是10

问题

当我们选择句子时: eq_range_index_dive_limit 花费了(0.01秒)

select * from user force index(job_id) where job_id in (1,2,3,4,5,6,7,8,9,10,11);

但是当我们选择句子时: explain select * from user force index(job_id) where job_id in (1,11)\G; *************************** 1. row *************************** id: 1 select_type: SIMPLE table: user partitions: NULL type: range possible_keys: job_id key: job_id key_len: 8 ref: NULL rows: 10979573 filtered: 100.00 Extra: Using where 花了(0.27秒)

select id from user force index(job_id) where job_id in (1,11)
explain select id from user force index(job_id) where job_id in (1,11)\G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: user
   partitions: NULL
         type: index
possible_keys: job_id
          key: job_id
      key_len: 8
          ref: NULL
         rows: 998143
     filtered: 100.00
        Extra: Using where; Using index

我们使用mysql> show index from USER \G; *************************** 1. row *************************** Table: user Non_unique: 0 Key_name: PRIMARY Seq_in_index: 1 Column_name: id Collation: A Cardinality: 913536 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL *************************** 2. row *************************** Table: user Non_unique: 1 Key_name: job_id Seq_in_index: 1 Column_name: job_id Collation: A Cardinality: 1 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: Visible: YES Expression: NULL ,发现optimizer trace在第二个SQL中发生。然后优化程序选择扫描表。

为什么第一个SQL没有选择扫描表? 为什么best_covering_index_scanselect id慢得多,而select *却和select name一样快?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...