I basically have two tables, a ‘server’ table and a ‘server_ratings’ table. I need to optimize the current query that I have (It works but it takes around 4 seconds). Is there any way I can do this better?
SELECT ROUND(AVG(server_ratings.rating), 0), server.id, server.name
FROM server LEFT JOIN server_ratings ON server.id = server_ratings.server_id
GROUP BY server.id;
Query looks ok, but make sure you have proper indexes:
idcolumn inservertable – probably primary key,server_idcolumn inserver_ratingstable,If it does not help, then add
ratingcolumn intoservertable and calculate it on a constant basis (see this answer about Cron jobs). This way you will save the time you spend on calculations. They can be made separately eg. every minute, but probably some less frequent calculations are enough (depending on how dynamic is your data).Also make sure you query proper table – in the question you have mentioned
serverstable, but in the code there is reference toservertable. Probably a typo 🙂