600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > MySQL 搜索指定时间范围数据 时间字段有索引但是还是很费时

MySQL 搜索指定时间范围数据 时间字段有索引但是还是很费时

时间:2021-05-17 15:46:48

相关推荐

MySQL 搜索指定时间范围数据  时间字段有索引但是还是很费时

问题分析

所遇情况:

数据库版本:5.6.38查询时使用时间类型,在status、closed、playback_state字段上都有索引几种查询语句

explain (select count(*)

from session

where status = 2

and playback_state = 1

and closed > '/10/17'

and closed < '-10-18');

explain (select count(*)

from session

where status = 2

and playback_state = 1

and closed like '-10-17%');

explain (select count(*)

from session

where status = 2

and playback_state = 1

and closed > 1539705600

and closed < 1539792000);

explain (select count(*)

from session

where status = 2

and playback_state = 1

and closed > unix_timestamp('/10/17')

and closed < unix_timestamp('-10-18'));

查询情况:第一种情况使用closed的索引,查询速度很快. 其他使用playback_state,因为playback_state相同的数据有很多,因此除第一种情况外,其他情况都很糟糕。

为什么其他几种情况未使用closed进行索引:

mysql查询时,不管有多少个单个索引或联合索引,永远只使用一个索引。

具体使用哪个索引进行查询,由mysql进行选择,会选择一个它认为最合适的一个字段。在以上情况中,其选择了playback_state,而非closed。

应对方案:

当语句执行太长时间,使用explain看一下查询情况,mysql是否使用了正确的索引。在有索引的字段上使用函数是会把索引去掉的。可以使用use index强制mysql使用固定索引可以考虑使用联合索引(开发不能随意改动数据库的表结构)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。