时间:2021-07-01 10:21:17 帮助过:23人阅读
对索引值进行范围查找。
#设置索引idx_fk_customer_id(customer_id)
EXPLAIN SELECT * FROM rental WHERE customer_id >= 373 AND customer_id < 400;
仅仅使用索引中的最左边列进行查询。比如组合索引(col1,col2,col3)能够被col1,col1+col2,col1+col2+col3的等值查询利用到的。
#创建索引idx_payment_date(payment_date,amount,last_update);
EXPLAIN SELECT * FROM payment WHERE payment_date=‘2006-02-14 15:16:03‘ AND last_update = ‘2006-02-15 22:12:32‘;
从结果可以看出利用了索引,但又row为182行,所有只使用了部分索引。
EXPLAIN SELECT * FROM payment WHERE amount=3.98 AND last_update=‘2006-02-15‘;
从结果看出,这次查询没有利用索引,进行了全表查找。
当查询列都在索引字段中。即select中的列都在索引中。
EXPLAIN SELECT last_update FROM payment WHERE payment_date=‘2005-08-19 21:21:47‘ AND amount=4.99;
extra部分Using index,说明不需要通过索引回表,Using index就是平时说的覆盖索引扫描(即找到索引,就找到了要查询的结果,不用再回表查找了)。
仅仅使用索引的第一列,并且只包含索引第1列的开头部分进行查找。
#创建索引idx_title_desc_part(title(10),description(20));
EXPLAIN SELECT title FROM film_text WHERE title LIKE ‘AFRICAN%‘;
EXPLAIN SELECT inventory_id FROM rental WHERE rental_date=‘2006-02-14 15:16:03‘ AND customer_id >= 300 AND customer_id <=400;
type=ref,说明使用了索引。
EXPLAIN SELECT * FROM payment WHERE rental_id IS NULL;
EXPLAIN SELECT * FROM actor WHERE last_name LIKE ‘%NI%‘;
#优化
EXPLAIN SELECT * FROM (SELECT actor_id FROM actor WHERE last_name LIKE ‘%NI%‘)a,actor b WHERE a.actor_id=b.actor_id;
EXPLAIN SELECT * FROM actor WHERE last_name=1;
#使用索引
EXPLAIN SELECT * FROM actor WHERE last_name=‘1‘;
EXPLAIN SELECT * FROM payment WHERE amount=3.98 AND last_update=‘2006-02-15 22:12:32‘;
如查询以“S”开头的标题的电影,返回记录比例比较大,mysql预估索引扫描还不如全表扫描。
EXPLAIN SELECT * FROM film_text WHERE title LIKE ‘S%‘;
EXPLAIN SELECT * FROM payment WHERE customer_id=203 OR amount=3.96;
(2)mysql优化之使用索引优化查询
标签:mysql 索引优化 索引