1

I just built a website and have realised that I need to have a top 3 highest rated albums.. I haven't built in something that keeps track of the ratings. Ratings are stored separately. Can someone show me how to put these together please.

SELECT id, name FROM albums LIMIT 3

SELECT rating FROM ratings WHERE url=CONCAT('albums/show/', album.id)

Let me just flesh it out a bit. I need to get back the following:

From the albums table. id, name. From the ratings table I need to get back the average rating. ROUND((rating+rating+rating) / total ratings)

The ratings. Users can rate everything on my website so I have a generic ratings table. The rating is stored with the url of the page it applies to. Hence, to get album ratings I need to have 'albums/show/{album_id}'. In hind sight I should have had a type and id field but it is a bit late now with a lunch iminient.

Any help is much appreciated.

1
  • 1
    Do you thing you could add the album Id to the ratings table? That would make your join MUCH more efficient. That CONCAT('albums/show/', a.id) in the join is going to kill performance Commented May 3, 2010 at 11:18

1 Answer 1

2
SELECT
  a.id,
  a.name,
  AVG(r.rating) AS average
FROM
    albums a
  LEFT JOIN
    ratings r
  ON
    r.url = CONCAT('albums/show/', a.id)
GROUP BY
  a.id
ORDER BY
  average DESC
LIMIT 3

(Untested, see AVG())

Sign up to request clarification or add additional context in comments.

1 Comment

@JasonS You're very welcome. Consider refactoring an ID and "reference name" (e.g., "albums") into the ratings table in order to optimize the query. Also, consider appending , a.id DESC to the ORDER clause to force secondary ordering if there is not (yet) 3 rated albums.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.