您的位置:首页 > 数据库

每天进步一点点——使用SQL提示

2015-08-20 17:32 435 查看

使用SQL提示

 

mysql>explain select count(*) from rental \G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: rental

        type: index

possible_keys: NULL

         key: idx_fk_staff_id

     key_len: 1

         ref: NULL

        rows: 16005

       Extra: Using index

1 row in set (0.00 sec)

 

ERROR:

No query specified

USE INDEX
明确指定使用哪个索引

mysql>explain select count(*) from rental use index (rental_date)\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: rental

        type: index

possible_keys: NULL

         key: rental_date

     key_len: 10

         ref: NULL

        rows: 16005

       Extra: Using index

1 row in set (0.00 sec)

 

ERROR:

No query specified

IGNORE INDEX
明确指定不使用哪个索引

mysql>explain select count(*) from rental ignore index(idx_fk_staff_id)\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

        table: rental

        type: index

possible_keys: NULL

         key: idx_fk_customer_id

     key_len: 2

         ref: NULL

        rows: 16005

       Extra: Using index

1 row in set (0.00 sec)

 

ERROR:

No query specified

FORCE INDEX
例如:当不强制使用索引的时候,因为大部分库存inventory_id的值都大于1的,因此Mysql会默认进行全表扫描而不使用索引。

mysql>explain select * from rental where inventory_id >1 \G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: rental

        type: ALL

possible_keys: idx_fk_inventory_id

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 16005

       Extra: Using where

1 row in set (0.00 sec)

 

ERROR:

No query specified

使用use index发现MySQL还是选择全表扫描。当使用forceindex进行提示时,即便使用索引的效率不是最高,MySQL还是选择使用了索引,这是MySQL留给用户的一个自行选择执行计划的权利。

mysql>explain select * from rental use index(idx_fk_inventory_id) whereinventory_id>1 \G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: rental

         type: ALL

possible_keys: idx_fk_inventory_id

         key: NULL

     key_len: NULL

         ref: NULL

        rows: 16005

       Extra: Using where

1 row in set (0.00 sec)

 

ERROR:

No query specified

加入FORCE INDEX提示后再此执行上面的SQL

mysql>explain select * from rental force index(idx_fk_inventory_id) whereinventory_id>1\G;

*************************** 1. row***************************

          id: 1

 select_type: SIMPLE

       table: rental

        type: range

possible_keys: idx_fk_inventory_id

         key: idx_fk_inventory_id

     key_len: 3

         ref: NULL

        rows: 8002

       Extra: Using index condition

1 row in set (0.00 sec)

 

ERROR:

No query specified

果然,执行计划中使用了FORCE INDEX后的索引。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: