2.关于like关键字
对于使用like的查询,需要注意的是只有列的%不在第一个字符索引才可能被使用。以下分别展示了使用like的查询,第一个是索引被使用的,第二个是索引未被使用的。
以下是代码片段:
mysql> explain select * from user where username like'lee%';
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
| 1 | SIMPLE| user | range | user | user | 152 | NULL | 1 | Using where |
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
1 row in set (0.00 sec)
mysql> explain select * from user where username like'%lee';
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
| 1 | SIMPLE| user | ALL | NULL | NULL | NULL | NULL | 2 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
1 row in set (0.00 sec)
mysql> explain select * from user where username like'lee%';
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
| 1 | SIMPLE| user | range | user | user | 152 | NULL | 1 | Using where |
+----+-------------+-------+-------+---------------+------+---------+------+------+---------+
1 row in set (0.00 sec)
mysql> explain select * from user where username like'%lee';
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
| 1 | SIMPLE| user | ALL | NULL | NULL | NULL | NULL | 2 | Using where |
+----+-------------+-------+------+---------------+------+---------+------+------+----------+
1 row in set (0.00 sec)
3. 查看索引使用情况
使用以下命令:
mysql> show status like 'Handler_read_key';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Handler_read_key | 0 |
+------------------+-------+
1 row in set (0.00 sec)
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| Handler_read_key | 0 |
+------------------+-------+
1 row in set (0.00 sec)
如果索引正在工作,那么Handler_read_key 会很高,如果查询中出现Handler_read_rnd_next的值很高,则表明查询低效,索引的应用并不合理。