Search code examples
mysqljoinsubqueryrating

Multiple joins to collect user ratings?


I have a table called quotes:

id date       content
80 2012-06-03 This is the first quote.
81 2012-06-05 Lorem Ipsum.

And a table called ratings:

rid uid qid rating
1   4   80  -1
2   4   81  1

The uid field refers to the logged-in user that made that rating. The quotes website is only available to logged-in users, and I want to be able to display quotes to the current user, including information indicating the quote's current rating, whether or not they have rated the quote, and if so, what they rated it as. Ratings can either be -1 or 1. Quotes are not associated with the user who submitted them.

If I want to fetch just one quote, I execute this query (e.g. quote 80 and user 4):

SELECT
  q.id AS qid, q.content, q.date,
  COALESCE(SUM(r.rating), 0) AS rating,
    (SELECT COALESCE(rating, 0) FROM ratings WHERE qid = 80 AND uid = 4 LIMIT 1)
      AS user_rated
  FROM quotes q
  LEFT JOIN ratings r ON q.id = r.qid
  WHERE q.id = 80
  GROUP BY q.id

How would I modify that to display more than one quote (i.e. not just quote ID 80), but keep the user_rated and rating info?

Thanks a lot!


Solution

  • SELECT
      q.id AS qid,
      q.content,
      q.date,
      COALESCE(SUM(r.rating), 0) AS rating,
      COALESCE(SUM(IF(r.uid = 4, r.rating, NULL)), 0) AS user_rated
    FROM quotes q
    LEFT JOIN ratings r ON q.id = r.qid
    GROUP BY q.id