Hi and thanks for taking a look at my issue.
The problem: I have 2 tables, one for ratings and one for profiles. 'ratings' contains one rating a row with a column that associates the row with an ID from 'profiles' named 'profileID'. 'ratings' has a column 'stars' that contains an int up to 5.
I want to get the top 5 profiles with the most ratings. I tried to get the SUM(ratings.stars) where rating.profileID = profiles.ID but that doesn't work out since i'm not that good at MySQL.
Thanks
SELECT a.ID, SUM(b.stars) TotalRating
FROM profiles a
INNER JOIN ratings b
ON a.ID = b.ProfileID
GROUP BY a.ID
ORDER BY TotalRating DESC
LIMIT 5
This will basically give the top 5 profiles that has the greatest ratings. One problem with this query is that it doesn't support ties.
Totalling the ratings would make a product that has 100 two star ratings appear above a product that has 10 five star ratings. Probably better to use an average for rank?
SELECT profiles.ID,AVG(stars) as avg_rating
FROM profiles,ratings
WHERE profiles.ID = ratings.profileID
GROUP BY profiles.ID
ORDER BY avg_rating DESC
LIMIT 5;
Your question states that you want to list the profiles with the most ratings. If that is the case use COUNT(stars) instead of AVG(stars):
SELECT profiles.ID,COUNT(stars) as cnt_rating
FROM profiles,ratings
WHERE profiles.ID = ratings.profileID
GROUP BY profiles.ID
ORDER BY cnt_rating DESC
LIMIT 5;
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.