原創你去了哪里 最后發布於2019-10-18 14:05:48 閱讀數 121 收藏
展開
1:use index:在你查詢語句表名的后面,添加use index來提供你希望mysql去參考的索引列表,就可以讓mysql不再考慮其他可用的索引。如:select * from table use index(name,age);
2:IGNORE INDEX 提示會禁止查詢優化器使用指定的索引。在具有多個索引的查詢時,可以用來指定不需要優化器使用的那個索引,還可以在刪除不必要的索引之前在查詢中禁止使用該索引。如:select * from table ignore index(name,age);
3:force index:強制mysql使用一個特定的索引。一般情況下mysql會根據統計信息選擇正確的索引,但是當查詢優化器選擇了錯誤的索引或根本沒有使用索引的時候,這個提示將非常有用。
需要注意的是use/ignore/force index(index)這里括號里的index是索引名,而不是列名。而且后面必須要加上where條件。
先查看表索引信息:
show index from student2\G
*************************** 1. row ***************************
Table: student2
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 4
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
*************************** 2. row ***************************
Table: student2
Non_unique: 1
Key_name: se
Seq_in_index: 1
Column_name: sex
Collation: A
Cardinality: 4
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
2 rows in set (0.07 sec)
可以看出列sex上有個普通索引,索引名是se。
explain select * from student2 where sex='a';
+----+-------------+----------+------------+------+---------------+------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+-------+------+----------+-------+
| 1 | SIMPLE | student2 | NULL | ref | se | se | 2 | const | 1 | 100.00 | NULL |
+----+-------------+----------+------------+------+---------------+------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)
使用到了sex列的索引,如果我們不想它sql語句使用sex列的索引,可以這樣寫:
explain select * from student2 ignore index(se) where sex='a';
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| 1 | SIMPLE | student2 | NULL | ALL | NULL | NULL | NULL | NULL | 4 | 33.33 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
可以看出這次並沒有使用到索引。
如果你這樣寫sql就會報錯:explain select * from student2 ignore index(sex) where sex='a';
ERROR 1176 (42000): Key 'sex' doesn't exist in table 'student2'
因為ignore index括號里要寫索引名,而不是列明。
————————————————
版權聲明:本文為CSDN博主「你去了哪里」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43740552/article/details/102623930