1

I have a question using MySQL. I have 2 tables, one with names of games and one with different ratings for the games. I want to be able to search for a game by name and see the average ratings for each game. So far I kind of managed to get the average rating, but I will only see the rating of 1 game instead of multiple entries. Here's my query so far:

SELECT games.name, CAST(AVG(reviews.rating) as decimal(6, 1)) AS average_rating
    FROM games
    JOIN reviews
    ON games.id = reviews.game
    WHERE games.name LIKE '%spider%'
    AND type = '7'
    AND rating != 0

I hope some of you smart people can help me out with this! Thanks, Robert

2 Answers 2

2

You have to use a GROUP BY clause on the proper field to get the average for each group, otherwise it will calculate the average of all rows. I guess it's games.id, but depends on your table schemata.

SELECT games.name, CAST(AVG(reviews.rating) as decimal(6, 1)) AS average_rating
FROM games
JOIN reviews
ON games.id = reviews.game
WHERE games.name LIKE '%spider%'
AND type = '7'
AND rating != 0
GROUP BY games.id;

Read more about so called aggregate functions

Sign up to request clarification or add additional context in comments.

Comments

2

You have to use GROUP BY games.name to separate out the different names. The problem is that AVG is a summary function that collapses the results. The GROUP BY breaks the results out.

SELECT games.name, CAST(AVG(reviews.rating) as decimal(6, 1)) AS average_rating 
FROM games 
  JOIN reviews ON games.id = reviews.game 
WHERE games.name LIKE '%spider%' AND type = '7' AND rating != 0
GROUP BY games.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.