我在下面的mysql数据库中有这个查询。该查询在大约 1-2 百万行上运行大约需要 6 秒。我有日期、uniqueuserid、collectiontype 的索引。
如何在 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
根据要求,我在查询之前使用“EXPLAIN”进行了分析
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