2016-04-22 54 views
0

我有这个查询计算基于日期每年的价值总和。MySQL:如何优化此QUERY?按年计算SUM(日期)

它的工作原理,但它是沉重的,需要在10K左右的记录

运行一分钟到2分钟有没有办法来优化这一点,或者以更有效的方式写?

"select departments sum(case when year(employment_date) = '1990' then 1 else 0 end) as '1990'," 
    + "sum(case when year(employment_date) = '2010' then 1 else 0 end) as '2010'," 
    + "sum(case when year(employment_date) = '2011' then 1 else 0 end) as '2011'," 
    + "sum(case when year(employment_date) = '2012' then 1 else 0 end) as '2012'," 
    + "sum(case when year(employment_date) = '2013' then 1 else 0 end) as '2013'," 
    + "sum(case when year(employment_date) = '2014' then 1 else 0 end) as '2014'," 
    + "sum(case when year(employment_date) = '2015' then 1 else 0 end) as '2015'," 
    + "sum(case when year(employment_date) = '2016' then 1 else 0 end) as '2016'," 
    + " count(departments.dept_id) as Total " 
    + "from employees inner join departments on employees.employee_id=departments.employee_id AND departments.dept_id = ?"; 


sample resuts 

    |departments | Total | 2010 | 2011 | 2012 | 2013 | 2014 | 2015 | 2016 | 
    |Data systems | 100 | 30 | 10 | 5 | 15 | 20 | 12 | 8 | 
    |Social ssmp | 70 | 10 | 10 | 15 | 15 | 4 | 6 | 10 | 
+0

这个查询看起来是错误的,就好像它的employment_date不在其中的那个年份那么它会计入总数。 –

+0

请提供'SHOW CREATE TABLE' –

回答

0

给这个镜头,看看它是否更快。

select sum(case when employment_year = '1990' then employee_count else 0 end) as '1990', 
    sum(case when employment_year = '2010' then employee_count else 0 end) as '2010', 
    sum(case when employment_year = '2011' then employee_count else 0 end) as '2011', 
    sum(case when employment_year = '2012' then employee_count else 0 end) as '2012', 
    sum(case when employment_year = '2013' then employee_count else 0 end) as '2013', 
    sum(case when employment_year = '2014' then employee_count else 0 end) as '2014', 
    sum(case when employment_year = '2015' then employee_count else 0 end) as '2015', 
    sum(case when employment_year = '2016' then employee_count else 0 end) as '2016', 
    sum(employee_count) as Total 
from 
    (select * from 
    (select count(*) as employee_count,year(employment_date) as employment_year 
     from employees inner join departments on employees.employee_id=departments.employee_id AND departments.dept_id = 1 
     group by year(employment_date) 
    )T1 
    where employment_year = 1990 
    or employment_year between 2010 and 2016 
    )T2; 

sqlfiddle

只要改变departments.dept_id = 1到任何dep_id你要寻找的。

1

在mysql中,提高查询性能的最佳方法之一是索引。具有索引的整个观点是通过减少表中需要的记录/行数来加速搜索查询检查。

CREATE INDEX Emp_index ON Employee (Employment_Date, Employee_Id); CREATE INDEX Dept_index ON Departments(Departments , Dept_Id);

请更多信息请参阅link

只是一个快速建议..作为索引花费你额外的写入和存储空间,所以如果你的应用程序需要更多的插入/更新操作,你可能想要使用没有索引的表,但是如果它需要更多的数据检索操作,应该去索引表。