I have this query below in a mysql database. The query is taking ~6 seconds to run on ~1-2 million rows. I have indexs on date, uniqueuserid, collectiontype.
How can I increase the performance of this query in mysql?
select
DATE_FORMAT(MIN(collection.date),'%Y-%m-%d %H:00') as date,
COUNT(distinct collection.uniqueuserid) as convertingusers,
SUM(case when collection.type = 1 then valueofitem end) as valueofitem,
SUM(case when collection.type = 1 then 1 end) as numofitems,
SUM(case when collection.type = 1 and collection.network = 1 then collection.valueofitem end) as col1valueofitem,
SUM(case when collection.type = 1 and collection.network = 1 then 1 end) as col1numofitem,
SUM(case when collection.type = 1 and collection.network = 2 then collection.valueofitem end) as col2valueofitem,
SUM(case when collection.type = 1 and collection.network = 2 then 1 end) as col2numofitem,
SUM(case when collection.type = 1 and collection.network = 3 then collection.valueofitem end) as col3valueofitem,
SUM(case when collection.type = 1 and collection.network = 3 then 1 end) as col3numofitem,
SUM(case when collection.type = 2 then collection.valueofitem end) as collectiontypeB,
SUM(case when collection.type = 3 then collection.valueofitem end) as collectiontypeC,
COUNT(distinct collection.uniqueuserid) as convertingusers
from collection
where collection.date > date_sub(now(),INTERVAL 3 WEEK)
group by DATE_FORMAT(collection.date,'%Y-%m-%d') order by collection.date DESC limit 500
As requested, I've run an analysis with "EXPLAIN" before the query
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY ALL 1196352 Using temporary; Using filesort
2 DERIVED collection ALL 1196352