在一些数据条数比较多的表中,会发现按主键排序速度很慢。我们来看一个案例
表(id为主键):
id | status | time |
---|---|---|
1 | 0 | 1580000000 |
2 | 1 | 1591000000 |
3 | 1 | 1592000000 |
4 | 1 | 1593000000 |
... | ... | ... |
索引:status、time两个字段建组合索引(index_1)
table存在了两个索引,分别是 status、time的组合索引index_1 和 id的PRIMARY索引。 但是mysql 在一个简单查询中,只能使用一个索引。
例sql:
select * from table force index(index_1) where status=1 and time>1588888888 order by id asc limit 10
当我们where查询条件强制使用了索引index_1时,PRIMARY索引就不会被使用,导致id排序的时候速度慢
解决方案: 利用索引中的字段进行排序
整改sql:
select * from table force index(index_1) where status=1 and time>1588888888 order by time asc limit 10
由于time字段在index_1索引中,那么根据time排序的话,在where条件和排序中都可以使用index_1索引完成,效率上就会高很多
网友评论