[英]MySQL - Why in this case a secondary index doesn't reduce the time of this query?
As part of an experiment I'm trying to optimise this query, and for this example I am using [The Employee database][1] provided by MySql. 作为实验的一部分,我正在尝试优化此查询,在本示例中,我使用的是MySql提供的[The Employee database] [1]。 The strategy I'm using is creating a secondary index on the birth_date attribute since theory texts recommend doing this on columns that are used in the WHERE clause.
我使用的策略是在birth_date属性上创建二级索引,因为理论文章建议在WHERE子句中使用的列上执行此操作。
By creating such index I was expecting a reduction in time of at least 40% but that is not the case with this query. 通过创建这样的索引,我期望将时间减少至少40%,但这种查询并非如此。 There doesn't seem to be an improvement in time, in fact it takes a bit longer on average.
时间似乎没有任何改善,实际上平均花费的时间更长。 Could anyone tell me why this is happening?
谁能告诉我为什么会这样吗?
SELECT employees.emp_no,
employees.departments.dept_name,
employees.first_name,
employees.last_name,
employees.birth_date,
year(curdate()) - year(birth_date) AS yearsOld
FROM employees.employees
INNER JOIN employees.dept_emp ON employees.dept_emp.emp_no = employees.emp_no
INNER JOIN employees.departments ON employees.departments.dept_no = employees.dept_emp.dept_no
WHERE year (birth_date) < 1953
ORDER BY emp_no ASC;
Results: 结果:
Without secondary index: 没有二级索引:
Time taken on average: 0.728 sec 平均耗时:0.728秒
After creating secondary index: 创建二级索引后:
CREATE INDEX myIndex2 ON employees(birth_date);
Time taken on average: 0.731 sec 平均耗时:0.731秒
You are not using the raw column value of birth_date
. 您没有使用
birth_date
的原始列值。 Only then an index can be used. 只有这样才能使用索引。 When using a function like
year()
indexes are useless. 当使用诸如
year()
类的函数时,索引是无用的。
To make use of the index you can do this instead: 要使用索引,您可以改为执行以下操作:
where birth_date >= '1953-01-01'
and birth_date < '1954-01-01'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.