mysql带日期函数查询运行缓慢

mlmc2os5  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(280)

我今天在执行查询时发现了一些奇怪的事情,我想知道这是怎么发生的。
以下是我的疑问:

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分钟。这里以datetime格式测试\u date列数据,例如:2020-06-01 00:00:00
这里的总记录规模超过700万条。

oymdgrw7

oymdgrw71#

不要对筛选的列使用函数。这使得查询不可访问,这意味着数据库不能利用现有索引。基本上,您是在强制数据库在进行筛选之前对列中的每个值进行计算。
如果要在给定的一天进行过滤,可以使用具有半开区间的不等式:

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

相关问题