08-确定问题并采取相应的优化措施
经过以上步骤,基本就可以确认问题出现的原因。此时用户可以根据情况采取相应的措施,进行优化以提高执行的效率。
在18.1.3小节的例子中,已经可以确认是对客户表customer的全表扫描导致效率的不理想,那么对客户表customer的email字段创建索引,具体如下:
mysql> create index idx_email on customer(email);
Query OK, 0 rows affected (0.37 sec)
Records: 0 Duplicates: 0 Warnings: 0
创建索引后,再看一下这条语句的执行计划,具体如下:
mysql> explain select sum(amount) from customer a, payment b where 1=1 and a.customer_id= b.customer_id and email = '[email protected]'\G
1. row
id: 1
select_type: SIMPLE
table: a
type: ref
possible_keys: PRIMARY,idx_email
key: idx_email
key_len: 153
ref: const
rows: 1
Extra: Using where; Using index
2. row
id: 1
select_type: SIMPLE
table: b
type: ref
possible_keys: idx_fk_customer_id
key: idx_fk_customer_id
key_len: 2
ref: sakila.a.customer_id
rows: 14
Extra:
2 rows in set (0.00 sec)
可以发现,建立索引后对客户表customer需要扫描的行数明显减少(从583行减少到1行),可见索引的使用可以大大提高数据库的访问速度,尤其在表很庞大的时候这种优势更为明显。