5

mysql查询中利用索引的机制

 3 years ago
source link: https://blogread.cn/it/article/5023?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

mysql查询中利用索引的机制

浏览:3803次  出处信息

    今天遇到一个奇怪的问题,明明已经建立了索引,select语句的explain也表明会利用这个索引,可是结果偏偏没有用索引,最后扫描了全表。

    两个结构完全一样的sql语句:

     sql1: select * from table where col_a = 123 and col_b in (‘foo’,\'bar’) order by id desc;

    sql2: select * from table where col_a = 456 and col_b in (‘foo’,\'bar’) order by id desc;

    结果sql1选择利用了col_a的索引,速度很快,sql2利用了主键ID的索引,扫描了全表(40w行)。

    仔细分析,发现数据库中,col_a=456的记录数有近1万条,而col_a=123的记录数只有几条。

    于是就清楚了,mysql选择索引不仅仅依据查询结构和索引结构,还会根据索引大概估算选择每种索引的数据量,然后选择他认为最快的索引。

    可能是主键索引会比普通index更快,所以mysql最后选择了数据量跟大的id索引。

    那么,如何解决这个问题呢?

     很简单,只要在order语句里写多个键即可,比如:order by col_a, id desc

建议继续学习:

QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK