鍍金池/ 問答/數(shù)據(jù)庫  網(wǎng)絡(luò)營(yíng)銷/ mysql 查詢使用 in 索引失效的問題?

mysql 查詢使用 in 索引失效的問題?

表中的數(shù)據(jù)是這樣的:

mysql> select * from tbl_student;
+----+----------+----------+---------------------+
| id | name     | class_id | create_time         |
+----+----------+----------+---------------------+
|  1 | James    |        1 | 2018-01-21 13:54:50 |
|  2 | Wade     |        1 | 2018-01-21 13:55:02 |
|  3 | Bosh     |        1 | 2018-01-21 14:04:45 |
|  4 | Paul     |        1 | 2018-01-21 14:04:54 |
|  5 | kobe     |        1 | 2018-01-21 14:05:14 |
|  6 | Rooney   |        2 | 2018-01-21 15:02:06 |
|  7 | Pogeba   |        2 | 2018-01-21 15:02:20 |
|  8 | Martia   |        2 | 2018-01-21 15:47:47 |
|  9 | Lingard  |        2 | 2018-01-21 15:48:15 |
| 10 | Simeone  |        2 | 2018-01-21 15:48:28 |
| 11 | Messi    |        2 | 2018-01-21 15:48:36 |
| 12 | Tina     |        2 | 2018-01-21 15:49:04 |
| 13 | Manu     |        2 | 2018-01-21 15:55:29 |
| 14 | Iversion |        1 | 2018-01-21 15:55:44 |
| 15 | Mata     |        1 | 2018-01-21 15:56:12 |
+----+----------+----------+---------------------+
15 rows in set (0.00 sec)

給字段 name 建立了索引

mysql> explain select * from tbl_student where name in ('Pogeba', 'Rooney');
+----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
| id | select_type | table       | partitions | type  | possible_keys | key  | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | tbl_student | NULL       | range | name          | name | 51      | NULL |    2 |   100.00 | Using index condition |
+----+-------------+-------------+------------+-------+---------------+------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)

當(dāng) in 有兩個(gè)值的時(shí)候索引有效

mysql> explain select * from tbl_student where name in ('Pogeba', 'Rooney', 'Paul');
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table       | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | tbl_student | NULL       | ALL  | name          | NULL | NULL    | NULL |   15 |    20.00 | Using where |
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.01 sec)

當(dāng) in 里面有三個(gè)值的時(shí)候索引就失效了,這是為什么?

回答
編輯回答
萌吟

mysql查詢優(yōu)化器認(rèn)為全表掃描時(shí)如果速度大于使用索引,就會(huì)不用索引,你可以使用FORCE INDEX強(qiáng)制mysql使用索引

2018年1月4日 00:51
編輯回答
柒喵

可以看看showporcess或者執(zhí)行計(jì)劃看mysql到底將語句優(yōu)化成什么樣

2017年9月5日 01:20