我有一张书桌,上面有一些书评;
这些是我为测试这个查询而创建的一些虚拟记录;

 ID    BookID   RatersID     Rating    Date
 1     2        3            5         (date)
 2     2        4            4         (date)


SELECT `RatersID`,
COUNT(*) AS `raters`, `Rating`, COUNT(*) AS `Ratings`
FROM
`BOOKS_ratings`
GROUP BY
`BookID`

当我运行我期望的查询时
BookID    Raters     Ratings
2         2          9

我得到的是:
RatersID    raters    Rating    Ratings
3           2         5         2

我不明白为什么会这样?
///////////////////上面已经回答了
我已经让查询工作了,但是当试图用php接收信息时,数字是重复的
例如Raters=2 PHP显示22
评分=9 PHP显示99
    $getratingq = mysqli_query($con,"SELECT `RatersID`, COUNT(*) AS `Raters`, sum(Rating) AS `Ratings` FROM `BOOKS_ratings` WHERE `BookID` ='$bookid' GROUP BY `BookID` LIMIT 1") or die("Get ratings query error");
if($getrating = mysqli_fetch_array($getratingq))
{
   echo $ratings = $getrating['Ratings'];
   $raters= $getrating['Raters'];
   $rating =  $ratings/$raters;
   $stars = floor("$rating");
}

最佳答案

您需要使用sum()来获得评分的总和

    SELECT
   `BookID`,
    COUNT(*) AS `raters`
    sum(Rating) as Ratings
    FROM
    `BOOKS_ratings`
    GROUP BY
    `BookID`

07-24 14:24