如何知道你建立的MySQL索引是高效,合理的

不管是開發人員,仍是數據庫維護人員,給表建立索引是很常見的事情。普通到什麼程度,初級,中級開發人員的印象中,只要寫的sql語句效率不高,第一反應就是建索引,而無論這個字段是否適合建立索引。反正只要給字段建立好索引,應用就能跑的嗖嗖的,索引就是銀彈,就是靈丹妙藥。mysql

案例
在某個項目現場的數據庫中,開發人員給一張業務表的全部字段都建立上了索引。因而就問,爲何建立這麼索引。開發說,我不懂sql怎麼優化,碰到慢了,就建立索引。sql

因此在接手一個新庫時,瞭解哪些索引不合理,低效是頗有必要的一件事情。數據庫

高效索引特色
索引必須建立在索引選擇性較高的列上,選擇性的計算方式爲ide

select count(distinct(col_name))/count(*) from tb_name

若是結果小於0.2,則不建議在此列上建立索引,不然大機率會拖慢SQL執行優化

查詢低效索引
能夠根據高效索引特色,即選擇性小於0.2的列上建立索引是低效的,能夠經過如下sql語句查詢到低效索引code

mysql> SELECT
    ->     t.TABLE_SCHEMA,t.TABLE_NAME,INDEX_NAME,CARDINALITY,
    ->     TABLE_ROWS, CARDINALITY/TABLE_ROWS AS SELECTIVITY
    -> FROM
    ->     information_schema.TABLES t,
    -> (
    ->   SELECT table_schema,table_name,index_name,cardinality
    ->   FROM information_schema.STATISTICS
    ->   WHERE (table_schema,table_name,index_name,seq_in_index) IN (
    ->   SELECT table_schema,table_name,index_name,MAX(seq_in_index)
    ->   FROM information_schema.STATISTICS
    ->   GROUP BY table_schema , table_name , index_name )
    -> ) s
    -> WHERE
    ->     t.table_schema = s.table_schema
    ->         AND t.table_name = s.table_name AND t.table_rows != 0
    ->         AND t.table_schema NOT IN ( 'mysql','performance_schema','information_schema','sys')
    ->         and index_name!='PRIMARY'
    ->         and CARDINALITY/TABLE_ROWS <=0.2
    -> ORDER BY SELECTIVITY;
+--------------+------------+------------+-------------+------------+-------------+
| TABLE_SCHEMA | TABLE_NAME | index_name | cardinality | TABLE_ROWS | SELECTIVITY |
+--------------+------------+------------+-------------+------------+-------------+
| sbtest       | sbtest1    | k_1        |       13167 |      79937 |      0.1647 |
+--------------+------------+------------+-------------+------------+-------------+
1 row in set (0.09 sec)

從上面結果就找到一個低效索引(k_1),經過下面的命令,能夠更詳細的獲取索引信息orm

mysql> show index from sbtest.sbtest1;
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| sbtest1 |          0 | PRIMARY  |            1 | id          | A         |       79937 |     NULL | NULL   |      | BTREE      |         |               |
| sbtest1 |          1 | k_1      |            1 | k           | A         |       13167 |     NULL | NULL   |      | BTREE      |         |               |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.00 sec)
相關文章
相關標籤/搜索