I have a table with some ratings for books;
These are some dummy records I have created to test this query out;
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`
When I run the query I expected
BookID Raters Ratings
2 2 9
What I get:
RatersID raters Rating Ratings
3 2 5 2
I do not understand why this is happening? /////////////////// Above has been answered
I have got the query working but when trying to receive the information in php the numbers are duplicated
E.g Raters = 2 PHP shows 22 Ratings = 9 PHP shows 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");
}
You need to use sum()
to get the sum of Rating
SELECT
`BookID`,
COUNT(*) AS `raters`
sum(Rating) as Ratings
FROM
`BOOKS_ratings`
GROUP BY
`BookID`