Background
We're using mysql 5.6 and encounter a serious slow query online.
The table can be simplified to
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 | |
+--------+--------------+------+-----+---------+----------------+
There are 1M rows and all job_id is ZERO.
We create job_id index named job_id.
eq_range_index_dive_limit is 10
Problem
When we select with sentence:
select * from user force index(job_id) where job_id in (1,2,3,4,5,6,7,8,9,10,11);
it cost (0.01 sec)
explain select * from user force index(job_id) where job_id in (1,2,3,4,5,6,7,8,9,10,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
but when we select with sentence:
select id from user force index(job_id) where job_id in (1,2,3,4,5,6,7,8,9,10,11)
it cost (0.27 sec)
explain select id from user force index(job_id) where job_id in (1,2,3,4,5,6,7,8,9,10,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
We used optimizer trace and we found best_covering_index_scan happened in the second SQL. And optimizer chosen scan table.
Why the first SQL didn't chose scan table?
Why select id is much slower than select *, and select name is as fast as select *?