前段時間,一大早上,就收到報警,警告php-fpm進程的數(shù)量超過閾值。最終發(fā)現(xiàn)是一條sql沒用到索引,導致執(zhí)行數(shù)據(jù)庫查詢慢了,最終導致php-fpm進程數(shù)增加。最終通過analyze table feed_comment_info_id_0000 命令更新了Cardinality ,才能再次用到索引。
排查過程如下:
sql語句:
1
|
select id from feed_comment_info_id_0000 where obj_id=101 and type=1; |
索引信息:
1
2
3
4
5
6
7
8
9
10
|
show index from feed_comment_info_id_0000 + ---------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | + ---------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ | feed_comment_info_id_0000 | 0 | PRIMARY | 1 | id | A | 6216 | NULL | NULL | | BTREE | | | feed_comment_info_id_0000 | 1 | obj_type | 1 | obj_id | A | 6216 | NULL | NULL | | BTREE | | | feed_comment_info_id_0000 | 1 | obj_type | 2 | type | A | 6216 | NULL | NULL | YES | BTREE | | | feed_comment_info_id_0000 | 1 | user_id | 1 | user_id | A | 6216 | NULL | NULL | | BTREE | | + ---------------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+ 5 rows in set (0.00 sec) |
通過explian查看時,發(fā)現(xiàn)sql用的是主鍵PRIMARY,而不是obj_type索引。通過show index 查看索引的Cardinality值,發(fā)現(xiàn)這個值是實際數(shù)據(jù)的兩倍。感覺這個Cardinality值已經(jīng)不正常,因此通過analyzea table命令對這個值從新進行了計算。命令執(zhí)行完畢后,就可用使用索引了。
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
總結(jié)一下:
1、它代表的是索引中唯一值的數(shù)目的估計值。如果是myisam引擎,這個值是一個準確的值。如果是innodb引擎,這個值是一個估算的值,每次執(zhí)行show index 時,可能會不一樣
2、創(chuàng)建Index時(primary key除外),MyISAM的表Cardinality的值為null,InnoDB的表Cardinality的值大概為行數(shù);
3、值的大小會影響到索引的選擇
4、創(chuàng)建Index時,MyISAM的表Cardinality的值為null,InnoDB的表Cardinality的值大概為行數(shù)。
5、可以通過Analyze table來更新一張表或者mysqlcheck -Aa來進行更新整個數(shù)據(jù)庫
6、可以通過 show index 查看其值