Reputation: 659
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
Upvotes: 1
Views: 74
Reputation: 1515
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
Upvotes: 2
Reputation: 3552
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
Upvotes: 2