MySQL - 如何改进这些查询?

时间:2013-02-14 15:22:28

标签: mysql

第一个:

SELECT MONTH(timestamp) AS d, COUNT(*) AS c 
FROM table
WHERE YEAR(timestamp)=2012 AND Status = 1
GROUP BY MONTH(timestamp)

我面临的一个问题是,我必须运行多个使用Status不同值的查询。有没有办法将它们合二为一?就像在一列中一样,它会包含Status=1时的所有计数以及Status=2时的其他列等。

第二个:

SELECT COUNT(*) c , MONTH(timestamp) t FROM
(
SELECT t.adminid, timestamp
FROM  table1 t 
LEFT JOIN admins a ON a.adminID=t.adminID
WHERE YEAR(timestamp)=2012          
GROUP BY t.adminID, DATE(Timestamp)
ORDER BY timestamp DESC
) AS a
GROUP BY MONTH(timestamp)
ORDER BY MONTH(timestamp) ASC;

嵌套查询,不确定我是否可以对此进行改进。我在2张桌子上运行这个,一个有~35k行,一个有~300k行。第一张桌子需要大约半秒钟,第二张桌子需要4-5秒钟。

1 个答案:

答案 0 :(得分:1)

这些可能会有所帮助:

第一个:

SELECT MONTH(timestamp) AS d, 
sum(case when Status=1 then 1 else 0 end) as Status1Count,
sum(case when Status=2 then 1 else 0 end) as Status2Count,
sum(case when Status=3 then 1 else 0 end) as Status3Count
FROM `table`
WHERE timestamp between '2012-01-01 00:00:00' and '2012-12-31 23:59:59' 
AND Status in (1,2,3)
GROUP BY MONTH(timestamp);

第二个:

确保timestamp列上有索引,然后确保您没有运行任何转化功能,例如索引列上的MONTH(timestamp)。像这样的东西:

SELECT COUNT(*) c , a.m as t FROM
(
SELECT t.adminid, timestamp, MONTH(timestamp) as m
FROM  table1 t 
LEFT JOIN admins a ON a.adminID=t.adminID
WHERE timestamp between '2012-01-01 00:00:00' and '2012-12-31 23:59:59'          
GROUP BY t.adminID, DATE(Timestamp)
ORDER BY timestamp DESC
) AS a
GROUP BY a.m
ORDER BY a.m ASC;

第二个有点棘手,因为我没有在我面前的数据,所以我看不到数据库访问路径!