今天在寫一個Perl腳本,想自動化查找出MySQL數據庫中可能無效的索引,於是根據朝陽的書上提到的一些規則,我來設計了一些判斷方法,其中發現某個我想要的值就是SHOW INDEX FROM table里的Cardinality,於是查了下它的含義以驗證我的想法。
MySQL中SHOW INDEX FROM table 會有以下結果列
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
我想知道的是Cardinality列的含義。
查看官方文檔的解釋:
An estimate of the number of unique values in the index. This is updated by running ANALYZE TABLE or myisamchk -a. Cardinality is counted based on statistics stored as integers, so the value is not necessarily exact even for small tables. The higher the cardinality, the greater the chance that MySQL uses the index when doing joins.
所以這個Cardinality會有如下的含義:
1. 列值代表的是此列中存儲的唯一值的個數(如果此列為primary key 則值為記錄的行數)
2. 列值只是個估計值,並不准確。
3. 列值不會自動更新,需要通過Analyze table來更新一張表或者mysqlcheck -Aa來進行更新整個數據庫。
4. 列值的大小影響Join時是否選用這個Index的判斷。
5. 創建Index時,MyISAM的表Cardinality的值為null,InnoDB的表Cardinality的值大概為行數。
6. MyISAM與InnoDB對於Cardinality的計算方式不同。
參考:
http://www.penglixun.com/tech/database/mysql_show_index_cardinality.html