I have a product order table in mysql. It’s like this:
create table `order`
(productcode int,
quantity tinyint,
order_date timestamp,
blablabla)
then, to get rate of rise, i wrote this query:
SELECT thismonth.productcode,
(thismonth.ordercount-lastmonth.ordercount)/lastmonth.ordercount as riserate
FROM ( (SELECT productcode,
sum(quantity) as ordercount
FROM `order`
where date_format(order_date,'%m') = 12
group by productcode) as thismonth,
(SELECT productcode,
sum(quantity) as ordercount
FROM `order`
where date_format(order_date,'%m') = 11
group by productcode) as lastmonth)
WHERE thismonth.productcode = lastmonth.productcode
ORDER BY riserate;
but it runs about 30s on my pc(200000 records, 200MB(include other fields)).
Are there any way to increase query speed? I already create index for productcode field.
I thought the reason of low performance is ‘GROUP BY’, is there any different way?
I tried your answers, but all of them seems not work, and I was wondering if there is something wrong with index(it’s not me who created them), so I delete all index and re-created them, everything goes fine — It only takes 3-4s. And difference between my query and yours is not very obvious. But REALLY thanks you guys, I learned a lot 🙂
Try adding an index on (ORDER_DATE, PRODUCTCODE) and change the query to eliminate the use of the DATE_FORMAT function, as in:
Share and enjoy.