我有以下SQL查询:
SELECT tblBooks.bookID,
tblBooks.title,
tblBooks.author,
tblBooks.coverImage,
ROUND(ROUND(tblReviews.rating * 2) / 2, 1) AS rating
FROM tblBooks
LEFT JOIN tblReviews
ON tblBooks.bookID = tblReviews.bookID
LEFT JOIN tblMembers
ON tblReviews.userID = tblMembers.userID
WHERE tblReviews.bookID IS NOT NULL
ORDER BY rating DESC
LIMIT 0, 40
我想查询数据库并返回平均评分,因此,如果某本书已被审核6次,则总计来自6个用户的每个评分并计算平均值。目前,仅返回最新的评分。当我将此行更改为:
ROUND(ROUND(AVG(tblReviews.rating) * 2) / 2, 1) AS rating
总共只返回了一个结果,因此显然存在错误,但是我不知道该怎么办。
如果有人可以对此进行说明,我认为这将与我的加入有关。
最佳答案
您需要像这样使用group by
:
SELECT tblBooks.bookID, tblBooks.title, tblBooks.author, tblBooks.coverImage,
AVG(tblReviews.rating) as avgRating
FROM tblBooks
LEFT JOIN tblReviews
ON tblBooks.bookID = tblReviews.bookID
WHERE tblReviews.bookID IS NOT NULL
group by tblBooks.bookID, tblBooks.title, tblBooks.author, tblBooks.coverImage
ORDER BY avgrating DESC
您的查询似乎没有使用Members表中的任何信息,因此我消除了它。它甚至都不基于它进行过滤,因为您正在使用
left join
。