Search code examples
mysqlsqlselectsql-optimization

How to minimize time in mySQL select query?


I have this query wherein I want to find out the sales for the current year and the sales for last year. I cannot make it into 2 separate queries since it has to be of the same item code. Meaning the item codes used in the sales for the current year must also be the item codes used for the sales last year.

The code below is working but it takes almost 8 to 9 minutes to fetch

select p.itemcode, 
       p.itemdescription, 
       (  select round((SUM(SA.QUANTITY*P.SellingPrice)),2) 
          from sales s 
          join product p on s.itemcode=p.itemcode 
          where YEAR(s.date) = 2013
       ),       
       (  select round((SUM(SA.QUANTITY * P.SellingPrice)),2) 
          from sales s 
          join product p on s.itemcode=p.itemcode 
          where YEAR(s.date) = 2012
       )
from product p 
join supplier s on p.suppliercode = s.suppliercode
join currency c on c.countrycode=s.countrycode
join country co on co.countrycode=c.countrycode
JOIN SALES SA ON SA.ITEMCODE=P.ITEMCODE
where c.countrycode = 'NZ'
group by p.itemcode
limit 10

Ideally the output should be

Itemcode    Itemdescription        SalesforCurrentYear    SalesforLastYear
GS771516    BUBBLE PARTY MACHINE   1035300.00             2079300.00
GSNBC-025   X'MAS HOUSE        600612.25              1397163.25
GSNBC-031   BRANDENBURGER TOR      741010.75              1572207.25

Thanks!!


Solution

  • The query can be simplified by eliminating two joins:

    select .......
           .......
    from product p 
    join supplier s on p.suppliercode = s.suppliercode
    JOIN SALES SA ON SA.ITEMCODE=P.ITEMCODE
    where s.countrycode = 'NZ'
    group by p.itemcode
    limit 10
    

    Afterwards, two dependent subqueries in the select clause can be reduced to one outer join:

    select p.itemcode, 
           p.itemdescription, 
           round((SUM(  CASE WHEN YEAR(s.date) = 2013
                        THEN SA.QUANTITY*P.SellingPrice  
                        ELSE 0 END
                )),2) As Sum2013,    
           round((SUM(  CASE WHEN YEAR(s.date) = 2012
                        THEN SA.QUANTITY * P.SellingPrice
                        ELSE 0 END
                )),2) As Sum2012
    from product p 
    join supplier s on p.suppliercode = s.suppliercode
    LEFT JOIN SALES SA ON SA.ITEMCODE=P.ITEMCODE
    where s.countrycode = 'NZ'
    group by p.itemcode
    limit 10
    

    Please try this query and let us know how it will perform.