I have a MySQL table of product ID's which has columns which show how many times each of these products has recieved a 1, 2, 3, 4 or 5 star rating from my customers. I would like to insert into the average rating column, which is currently blank, a figure to indicate what the average rating for each product is.
How can I calculate what the average rating for each product ID is and then modify the table to insert this average rating into the average rating column? I would then ideally like to run this SQL statement daily using a php script and a cron job to recalculate the average rating and update this table as more ratings are recorded for each product.
An example of the layout of the table is below:
Product ID | 1 | 2 | 3 | 4 | 5 | Average Rating
1294518 | 0 | 3 | 3 | 2 | 4 | ?
9226582 | 0 | 0 | 1 | 0 | 0 | ?
3946583 | 0 | 3 | 6 | 1 | 0 | ?
7392588 | 1 | 0 | 0 | 0 | 0 | ?
1196585 | 0 | 1 | 0 | 5 | 6 | ?
4285385 | 0 | 2 | 3 | 3 | 1 | ?
Have you tried:
UPDATE table
SET aveRate = (rate1 + rate2*2 + rate3*3 + rate4*4 + rate5*5) /
(rate1 + rate2 + rate3 + rate4 + rate5)
Am I missing something?