USING MYSQL
I had to create an average field for a table Movies to hold the average score for each movie. The actual scores are held in a table Ratings, which references Movies by mid (movie id). How would you go about updating each row in movies with the average found from the column "score" in Ratings?
I tried JOINS but they don't seem to work with MySQL. Any suggestions? Thank you in advance!
You can do this with an update
and join
:
update movies m join
(select mid, avg(score) as avgscore
from ratings r
group by mid
) r
on m.mid = r.mid
set m.avgscore = r.avgscore;
Of course, this will update the value only once. If you want to keep the averages up-to-date, then you need to create a trigger to re-set the value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.