0

第一:

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

我面临的问题之一是我必须运行多个使用不同值的查询Status。有没有办法将它们组合成一个?就像在一列中一样,它将包含 when 的所有计数Status=1和另一列的 whenStatus=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秒。

4

1 回答 1

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;

Second one is a bit tricky since I do not have the data in front of me so I can't see the DB access path!

于 2013-02-14T16:28:26.150 回答