在mysql查詢語句中能夠經過指定index_hint來告訴優化器如何使用索引,詳細能夠參考這裏html
index_hint:
USE {INDEX|KEY}
[FOR {JOIN|ORDER BY|GROUP BY}] ([index_list])
| IGNORE {INDEX|KEY}
[FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
| FORCE {INDEX|KEY}
[FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
查詢語句中使用index_hint時,若是index_hint指定的索引不存在,那麼服務器會返回錯誤ERROR 1176 (42000)。能夠看下面的例子mysql
drop table t1;
create table t1(id int auto_increment, a char(2), primary key (id), key idx1(a)) engine=innodb;
insert into t1 values (1,'ab');
select * from t1 force index (idx1) where a='ab';
+----+------+
| id | a |
+----+------+
| 1 | ab |
+----+------+
1 row in set (0.00 sec)
alter table t1 drop key idx1;
select * from t1 force index (idx1) where a='ab';
ERROR 1176 (42000): Key 'idx1' doesn't exist in table 't1'
在實際應用中,若是查詢語句使用index_hint指定了索引,隨着業務的發展,這個索引能變得多餘了,但刪除這個索引會致使應用報錯。因而要麼保留着個無用的索引,要麼修改sql從新發布應用。這兩個作法都不太友好。sql
若是index_hint指定的索引不存在,服務器不返回錯誤,而是選擇報warining,那麼刪除這個索引就不會致使應用報錯。服務器
改進:優化
新增sql_mode的類型INDEX_HINE_ERROR;spa
當sql_mode設置了INDEX_HINE_ERROR類型,若是index_hint指定的索引不存在,服務器返回錯誤。code
當sql_mode沒有設置INDEX_HINE_ERROR類型,若是index_hint指定的索引不存在,服務器不返回錯誤,而是選擇報warininghtm
看下面的例子:blog
1)sql_mode沒有設置INDEX_HINE_ERROR類型索引
set sql_mode='';
select * from t1 force index (idx1) where a='ab';
+----+------+
| id | a |
+----+------+
| 1 | ab |
+----+------+
1 row in set, 1 warning (0.00 sec)
show warnings;
+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1176 | Key 'idx1' doesn't exist in table 't1' |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
explain select * from t1 force index (idx1) where a='ab';
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | t1 | ALL | NULL | NULL | NULL | NULL | 1 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+-------------+
1 row in set, 1 warning (0.00 sec)
show warnings;
+---------+------+----------------------------------------+
| Level | Code | Message |
+---------+------+----------------------------------------+
| Warning | 1176 | Key 'idx1' doesn't exist in table 't1' |
+---------+------+----------------------------------------+
1 row in set (0.00 sec)
2)sql_mode設置了INDEX_HINE_ERROR類型
set sql_mode='index_hint_error';
select * from t1 force index (idx1) where a='ab';
ERROR 1176 (42000): Key 'idx1' doesn't exist in table 't1'
explain select * from t1 force index (idx1) where a='ab';
ERROR 1176 (42000): Key 'idx1' doesn't exist in table 't1'