《Mysql實(shí)例簡(jiǎn)單解析MySQL中的cardinality異常》要點(diǎn):
本文介紹了Mysql實(shí)例簡(jiǎn)單解析MySQL中的cardinality異常,希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
MYSQL必讀前段時(shí)間,一大早上,就收到報(bào)警,警告php-fpm進(jìn)程的數(shù)量超過(guò)閾值.最終發(fā)現(xiàn)是一條sql沒(méi)用到索引,導(dǎo)致執(zhí)行數(shù)據(jù)庫(kù)查詢慢了,最終導(dǎo)致php-fpm進(jìn)程數(shù)增加.最終通過(guò)analyze table feed_comment_info_id_0000 命令更新了Cardinality ,才能再次用到索引.
排查過(guò)程如下:
sql語(yǔ)句:
MYSQL必讀
select id from feed_comment_info_id_0000 where obj_id=101 and type=1;
MYSQL必讀索引信息:
MYSQL必讀
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)
MYSQL必讀通過(guò)explian查看時(shí),發(fā)現(xiàn)sql用的是主鍵PRIMARY,而不是obj_type索引.通過(guò)show index 查看索引的Cardinality值,發(fā)現(xiàn)這個(gè)值是實(shí)際數(shù)據(jù)的兩倍.感覺(jué)這個(gè)Cardinality值已經(jīng)不正常,因此通過(guò)analyzea table命令對(duì)這個(gè)值從新進(jìn)行了計(jì)算.命令執(zhí)行完畢后,就可用使用索引了.
MYSQL必讀Cardinality解釋
官方文檔的解釋?zhuān)?br>
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ù)目的估計(jì)值.如果是myisam引擎,這個(gè)值是一個(gè)準(zhǔn)確的值.如果是innodb引擎,這個(gè)值是一個(gè)估算的值,每次執(zhí)行show index 時(shí),可能會(huì)不一樣
2、創(chuàng)建Index時(shí)(primary key除外),MyISAM的表Cardinality的值為null,InnoDB的表Cardinality的值大概為行數(shù);
3、值的大小會(huì)影響到索引的選擇
4、創(chuàng)建Index時(shí),MyISAM的表Cardinality的值為null,InnoDB的表Cardinality的值大概為行數(shù).
5、可以通過(guò)Analyze table來(lái)更新一張表或者mysqlcheck -Aa來(lái)進(jìn)行更新整個(gè)數(shù)據(jù)庫(kù)
6、可以通過(guò) show index 查看其值
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.snjht.com/jiaocheng/5310.html