2016-04-22 53 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

只是一個快速建議..作爲索引花費你額外的寫入和存儲空間,所以如果你的應用程序需要更多的插入/更新操作,你可能想要使用沒有索引的表,但是如果它需要更多的數據檢索操作,應該去索引表。