关于索引cardinality的知识

25 篇文章 0 订阅
5 篇文章 0 订阅
1. cardinality简单的说就是,你索引列的唯一值的个数,如果是复合索引就是唯一组合的个数。
2. 这个数值将会作为mysql优化器对语句执行计划进行判定时依据。如果唯一性太小,那么优化器会认为,这个索引对语句没有太大帮助,而不使用索引。
3. cardinality值越大,就意味着,使用索引能排除越多的数据,执行也更为高效。



举几个例子吧:a、b、c这里是列名
a,b,c
1,1,1
1,1,2
1,2,1
1,2,2
2,1,1
2,1,2
2,2,1
2,2,2
假如你对a列作索引,那么它的cardinality就是2,因为此列只有1和2两个值。
假如你对a,b列作复合索引,那么它的cardinality就是4,因为这两列有(1,2),(1,1),(2,1),(2,2)这几种组合。
假如你对a,b,c作复合索引,那么它的cardinality就是8.........


官方文档的解释:
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. 列值只是个估计值,并不准确。(我用的innodb数据库实际的例子中这个值也不是太准确)
3. 列值不会自动更新,需要通过analyze table来进行更新。
4. 列值的大小影响join时是否选用这个index的判断。
5. 初建index时,MyISAM的表cardinality的值为null,InnoDB的表cardinality的值大概为行数。
6. MyISAM与InnoDB对于cardinality的计算方式不同。

以下是本人的测试结果

select count(*) from net_user;

20761

select count(distinct userId) from net_user;

20761

show index from net_user;

 TableNon_uniqueKey_nameSeq_in_indexColumn_nameCollationCardinalitySub_partPackedNullIndex_typeCommentIndex_comment
 net_user0PRIMARY1userIdA20587   BTREE  
 net_user0username1usernameA20587   BTREE  
 net_user1lastLogin1lastLoginA20587   BTREE  
 net_user1doctorId1doctorIdA20587   BTREE  

analyze local table net_user;

nethospital.net_useranalyzestatusOK

show index from net_user;

net_user0PRIMARY1userIdA20624   BTREE  
net_user0username1usernameA20624   BTREE  
net_user1lastLogin1lastLoginA20624   BTREE  
net_user1doctorId1doctorIdA20624   BTREE  

此时索引已经修复,查询效率会有所提高。

需要注意的是,如果开启了binlog,那么Analyze Table的结果也会写入binlog,我们可以在analyze和table之间添加关键字local取消写入。



  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值