I want to calculate moving averages, common in stock charts, by pulling prices from a MySQL table. Being a newbie in both php and mysql, I need some advice for an efficient solution!
To see what I want, here's an example that DOES NOT work!
$period = 50;
for ($i=0;$i<10;$i++) {
$result = mysql_query("SELECT AVG(price) AS mov_avg FROM stock LIMIT ".$i.", ".$period);
$mov_avg = mysql_fetch_row($result);
echo $mov_avg[0]."<br>";
}
As you see, I want to calculate an average of 50 prices, and do it 10 times by moving one row forward in the table for each calculation. This example obviously does not work, since LIMIT limits the result of the query (which is a single row and field, the average), not the table itself, that I want.
So how do I rewrite this to do what I want? But even if it had worked it would not have been very efficient, calling mysql_query many times.
Is there a way to do all the calculations in the SELECT query? Subquery? Temporary table?
Or is it better to get all prices with a simple SELECT price FROM stock, and then do all the averaging in php?
In the latter case, what would be the most efficient way? There are no avg functions in php, as far as I know. I will need to do several hundreds of average calculations, so it need to be as efficient as possible.
Thanks in advance.