我有一个使用MySQL的问题。我有2个桌子,一个有游戏名称,一个有不同的游戏等级。我希望能够按名称搜索游戏并查看每个游戏的平均评分。到目前为止,我有点获得了平均评分,但我只会看到1个游戏而不是多个条目的评级。到目前为止,这是我的查询:
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
我希望你们中的一些聪明人可以帮助我解决这个问题! 谢谢,罗伯特
答案 0 :(得分:1)
您必须使用GROUP BY games.name
来分隔出不同的名称。问题是AVG
是一个汇总结果的汇总函数。 GROUP BY
会将结果分解。
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
答案 1 :(得分:1)
您必须在正确的字段上使用GROUP BY
子句来获取每个组的平均值,否则它将计算所有行的平均值。我猜它是games.id
,但取决于你的表格架构。
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;
详细了解所谓的aggregate functions