I have the following query which calculates a 7 day rolling average, however currently it takes 4 minutes to run due to the WHERE b.serverId = a.serverId
line. My question is how can I improve this query so that it takes miliseconds to seconds? The test dataset is ~250k rows.
SELECT a.serverId,
s.serverName,
a.playersOnline,
DATE(a.pingTime) AS pingDate,
Round( ( SELECT SUM(b.playersOnline) / COUNT(b.playersOnline)
FROM pings AS b
WHERE b.serverId = a.serverId AND
DATEDIFF(a.pingTime, b.pingTime) BETWEEN 0 AND 6
), 2 ) AS '7dayMovingAvg'
FROM pings AS a
JOIN `server` AS s
ON s.serverId = a.serverId
WHERE a.serverId = 1
GROUP BY pingDate
ORDER BY a.pingTime;
The tables:
Server table
serverId - PK, indexed
serverIp varchar
serverPort int(16)
serverName varchar
enabled tinyint(1)
Pings table
serverId FK, indexed (references Server table)
pingTime datetime, indexed
playersOnline int(5)
playersMax int(5)