mysql - An indexed MySQL query performs better with a 1 than a 0
问题描述
I have the following query where Date
has data-type non-nullable date-time
, GroupingId
has data-type non-nullable int
and IsCompleted
has data-type non-nullable tinyint(1)
.
SELECT
*
FROM
Table
WHERE
Date < @TimeNow
AND
GroupingId = @GroupingId
AND
IsCompleted = 0;
I have an index on this table of GroupingId
, Date
, IsCompleted
in that order.
For some reason if I run this query with t.IsCompleted = 0
, it performs a lot slower than t.IsCompleted = 1
every time.
I'm thinking that it may not be indexed effectively but could do with some help on it.
EDIT
I've updated the example query to make it a lot clearer. When IsCompleted = 0
is set, it returns far fewer rows and takes a lot longer than when IsCompleted = 1
is set
解决方案
您的查询不能使用索引进行排序。因此,查询的性能将由匹配where
条件的行数驱动。据推测,拥有的项目IsCompleted = 0
多于IsCompleted = 1
。
此查询的更好索引是(groupingId, isCompleted, date)
. 前两个键可以按任意顺序排列。
这个条件:
((t.Date >= @StartDate AND t.Date < @EndDate) OR (t.Date < @TimeNow))
也有点奇怪。我希望大多数或所有日期都在过去。假设它@TimeNow
代表当前日期,这将返回所有行。
推荐阅读
- javascript - 尝试导入错误:“Outlet”未从“react-router-dom”导出
- javascript - 我们如何创建像“arguments”这样的类数组对象?
- python - 使用 Pandas 导入数据时遇到错误
- flutter - Flutter:使用多个图像资产后应用程序崩溃
- python - 调用时类内的函数不起作用(python)
- neo4j - 我如何找到 neo4j 密码?
- python - 使用 Selenium 和 python 在网页上查找文本,然后直接在其下方获取文本
- c++ - 除非在应用程序窗口外单击,否则 WM_COMMAND 无法完成请求,
- javascript - 有没有比我这样做更有效的方法来排序标题数组(没有前导引号或文章)?
- r - R:四舍五入到不同的阈值