首页 > 解决方案 > 带有日期函数查询的mysql运行缓慢

问题描述

我今天在执行查询时发现了一些奇怪的东西,我想知道这是怎么发生的。

以下是我的查询:

select sum(price) as total from table_a where testing_date = '2020-06-10' 

此查询在搜索数据时需要 2-5 秒。现在我在查询中做了如下的小改动:

select sum(price) as total from table_a where date(testing_date) = '2020-06-10' 

在这种情况下,查询需要 2-3 分钟。这里 testing_date 列数据采用 dateTime 格式,例如:2020-06-01 00:00:00

这里的总记录大小超过 700 万。

标签: mysqlsqlselectquery-optimizationwhere-clause

解决方案


不要在您过滤的列上使用函数。这使得查询不可 SARGeable,这意味着数据库无法利用现有索引。基本上,您是在强制数据库在过滤发生之前对列中的每个值进行计算。

如果要在给定的日期进行过滤,可以使用具有半开区间的不等式:

where testing_date >= '2020-06-10' and testing_date < '2020-06-11'

推荐阅读