我正在尝试编写一个查询来创建一个数据“表”,如下所示:
SELECT cs.`category_id`, cs.`ProcessDate`, cs.`PercentChange`
FROM `Category_Statistics` cs
WHERE cs.`ProcessDate` >= '2011-05-10'
AND cs.`ProcessDate` <= '2011-05-14'
这将返回如下内容:
CategoryId | ProcessDate | PercentChange
-------------------------------------------
category_4 | 2011-05-10 | 10
category_4 | 2011-05-11 | 18
category_4 | 2011-05012 | 12
...
category_7 | 2011-05-10 | 21
category_7 | 2011-05-11 | 7
...
category_12 | 2011-05-10 | 7
category_12 | 2011-05-11 | 15
现在我希望结果是这样的(来自 MySQL 查询,而不是由应用程序操作):
CategoryId | 2011-05-10 | 2011-05-11 | 2011-05-12 | 2011-05-13 | 2011-05-14 |
--------------------------------------------------------------------------------
category_4 | 10 | 18 | 12 | 9 | 14 |
category_7 | 21 | 7 | 16 | 14 | 13 |
categeory_12 | 7 | 15 | 11 | 19 | 8 |
--------------------------------------------------------------------------------
我有查询来构建上述结果。这是我的查询。
SELECT `CategoryId`,
MAX(IF(c.`ProcessedOn` = '2011-04-20', c.`PercentChange`, NULL)) AS '2011-04-20',
MAX(IF(c.`ProcessedOn` = '2011-04-21', c.`PercentChange`, NULL)) AS '2011-04-21',
MAX(IF(c.`ProcessedOn` = '2011-04-22', c.`PercentChange`, NULL)) AS '2011-04-22',
MAX(IF(c.`ProcessedOn` = '2011-04-23', c.`PercentChange`, NULL)) AS '2011-04-23',
MAX(IF(c.`ProcessedOn` = '2011-04-24', c.`PercentChange`, NULL)) AS '2011-04-24'
FROM `Category_Gravity` c
WHERE c.`ProcessedOn` >= '2011-04-20'
AND c.`ProcessedOn` <= '2011-04-24'
GROUP BY `CategoryId`
当我有 20 或 100 条记录时,此查询工作正常。但是如果记录数是十万甚至更多,它就会变慢。我必须等待 10 分钟才能查看查询结果。请提供任何建议以加快我的查询或给我更好的查询来构建我的结果。