MySQL:如何优化此QUERY?按年(日期)计算SUM

时间:2016-04-22 03:38:27

标签: mysql query-optimization

我有这个查询,用于根据日期计算每年的值总和。

它有效,但很重,在大约10k记录上运行需要1分钟到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   |

2 个答案:

答案 0 :(得分:1)

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

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

请参阅link了解详情。

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

答案 1 :(得分: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。