我有这个查询计算基于日期每年的价值总和。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 |
这个查询看起来是错误的,就好像它的employment_date不在其中的那个年份那么它会计入总数。 –
请提供'SHOW CREATE TABLE' –