mit*_*ali 3 mysql sql query-optimization where-clause date-arithmetic
我今天在执行查询时发现了一些奇怪的事情,我想知道这是如何发生的。
以下是我的查询:
select sum(price) as total from table_a where testing_date = '2020-06-10'
Run Code Online (Sandbox Code Playgroud)
此查询在搜索数据时需要 2-5 秒。现在我对查询做了一些小更改,如下所示:
select sum(price) as total from table_a where date(testing_date) = '2020-06-10'
Run Code Online (Sandbox Code Playgroud)
在这种情况下,查询需要 2-3 分钟。这里的testing_date列数据采用日期时间格式,例如:2020-06-01 00:00:00
这里的总记录大小超过 700 万条。
不要在您筛选的列上使用函数。这使得查询不可 SARGeable,这意味着数据库无法利用现有索引。基本上,您强制数据库在进行过滤之前对列中的每个值进行计算。
如果要过滤给定的一天,可以使用半开区间的不等式:
where testing_date >= '2020-06-10' and testing_date < '2020-06-11'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2116 次 |
| 最近记录: |